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.

Conclusion: Mastering virtual, override, and new is essential for working confidently with inheritance in C#, since misusing them can silently introduce bugs that are difficult to trace back to their source.

Ready to Master C# Programming Course?

Join Uncodemy's hands-on training program with expert mentors and real-world projects.