Why need to use "virtual" keyword when we can use "new" keyword
The virtual
and new
keywords serve different purposes and have different implications in object-oriented programming.
virtual
Keyword:When a method, property, indexer, or event is marked as
virtual
in the base class, it allows derived classes to provide their own implementation for that member using theoverride
keyword.Using
virtual
indicates that the member is designed to be overridden in derived classes, promoting polymorphic behavior where the specific implementation is determined at runtime based on the type of the object.
new
Keyword:The
new
keyword allows derived classes to hide members of the same name and signature from the base class without overriding them. It essentially creates a new member in the derived class that happens to have the same name as a member in the base class.Unlike
override
,new
does not participate in polymorphism. When you call a method using the base class reference but the actual object is of the derived class, the behavior depends on the reference type. If the reference type is of the base class, it calls the base class member. If the reference type is of the derived class, it calls the derived class member.
So, the reason why you might want to use virtual
instead of new
is to enable polymorphic behavior and allow derived classes to provide their own implementations of a member. This is particularly useful in scenarios where you want to define a common interface or behavior in the base class but allow different implementations in derived classes. On the other hand, new
is used when you want to hide a member from the base class in the derived class without overriding it and without polymorphic behavior. Each has its own use case depending on the desired behavior and design of your classes.
Example:
Sure, let's illustrate the difference between using virtual
and new
with an example:
Suppose we have a base class Animal
with a method MakeSound
, and we want to allow derived classes to provide their own implementations of this method.
Using
virtual
andoverride
:
In this example:
The
MakeSound
method in theAnimal
class is marked asvirtual
, indicating that it can be overridden in derived classes.Both
Dog
andCat
classes override theMakeSound
method with their own implementations.When calling
MakeSound
on objects of typeAnimal
, the actual implementation called depends on the runtime type of the object. This is polymorphic behavior.
Using
new
:
In this example:
The
MakeSound
method in bothDog
andCat
classes is marked with thenew
keyword, indicating that they are hiding the method from the base class without overriding it.When calling
MakeSound
on objects of typeAnimal
, regardless of the actual runtime type of the object, the method from the base class is always called. This is becausenew
does not participate in polymorphism; the method called is determined by the compile-time type of the reference.
Last updated