Understanding virtual, override and new keyword in C#
Learn the differences between the virtual, override, and new keywords in C# and how they control method behavior in inheritance hierarchies.
The virtual Keyword
Marking a method as virtual in a base class allows derived classes to provide their own implementation of that method, enabling polymorphism where the correct version is chosen at runtime based on the object's actual type.
The override Keyword
A derived class uses the override keyword to replace the implementation of a virtual (or abstract) method inherited from its base class, ensuring the new behavior is used whenever the method is called through a base reference.
The new Keyword for Method Hiding
When a derived class uses new instead of override, it hides the base class method rather than overriding it. This means the method called depends on the type of the reference used, not the actual object type, which can lead to unexpected behavior if misunderstood.
Choosing the Right Approach
In general, override should be used when you want true polymorphic behavior, while new should be reserved for rare cases where you intentionally want to break the inheritance chain for a specific method.
.png)