Why should virtual methods be explicitly overridden in C#?
If you don't add the override
keyword, the method will be hidden (as if it had the new
keyword), not overridden.
For example:
class Base {
public virtual void T() { Console.WriteLine("Base"); }
}
class Derived : Base {
public void T() { Console.WriteLine("Derived"); }
}
Base d = new Derived();
d.T();
This code prints Base
.
If you add override
to the Derived
implementation, the code will print Derived
.
You cannot do this in C++ with a virtual method. (There is no way to hide a C++ virtual method without overriding it)