More with override in C#
Not Using "virtual" keyword
If you don't use the virtual
keyword in the base class, you won't be able to use the override
keyword in the derived class to override that method, property, indexer, or event. In this case, if you want to redefine the behavior of a method in the derived class without using virtual
or override
, you can use the new
keyword.
Here's an example illustrating the use of the new
keyword instead of override
when the method in the base class is not declared as virtual
:
Method without using
virtual
andoverride
:
In the above example:
The
Speak
method in theAnimal
class is not declared with thevirtual
keyword.In the
Dog
class, thenew
keyword is used to redefine theSpeak
method.When calling the
Speak
method on a variable of typeAnimal
but referencing aDog
object, theSpeak
method of the base classAnimal
is called, not that of the derived classDog
.
Property without using
virtual
andoverride
:
In this example:
The
Name
property in theAnimal
class is not declared with thevirtual
keyword.In the
Dog
class, thenew
keyword is used to redefine theName
property.When accessing the
Name
property on a variable of typeAnimal
but referencing aDog
object, theName
property of the base classAnimal
is called, not that of the derived classDog
.
In summary, if you don't use the virtual
keyword, you won't be able to override methods, properties, indexers, or events using the override
keyword. Instead, you can use the new
keyword to redefine them in the derived class. However, this does not change the behavior when calling those members through a base class type variable.
Only using "override" keyword
Not using "new" keyword
If you don't use the new
keyword and you're not using override
, the behavior depends on whether the method, property, indexer, or event in the derived class has the same signature as the member in the base class.
Method without using
override
ornew
:
In this example:
The
Speak
method in theDog
class has the same signature as the one in theAnimal
class (same name and parameters).When calling
Speak
on a variable of typeAnimal
but referencing aDog
object, theSpeak
method of theDog
class is called. This is because the compiler uses the most derived version of the method available at compile time, which is the one in theDog
class.
Property without using
override
ornew
:
Similarly:
The
Name
property in theDog
class has the same signature as the one in theAnimal
class.When accessing the
Name
property on a variable of typeAnimal
but referencing aDog
object, theName
property of theDog
class is called. This is because the compiler uses the most derived version of the property available at compile time, which is the one in theDog
class.
So, without using override
or new
, if the method, property, indexer, or event in the derived class has the same signature as the member in the base class, it replaces (hides) the member in the base class.
Last updated