override versus new (method hiding)
A favourite interview question: what prints when a derived object is used through a base-type variable?
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
override replaces the base method for the object, whatever variable it is seen through. new only hides the base method: which one you get depends on the type of the variable you call it on.
Code
class Base {
public virtual string Who() => "Base";
public string Tag() => "Base";
}
class Derived : Base {
public override string Who() => "Derived";
public new string Tag() => "Derived"; // hides, does not override
}
Base x = new Derived();
Console.WriteLine(x.Who()); // Derived: uses the object's type
Console.WriteLine(x.Tag()); // Base: uses the variable's type
Derived y = (Derived)x;
Console.WriteLine(y.Tag()); // DerivedTips
- Rule of thumb: virtual + override follows the object. Everything else follows the variable.
- Hiding with new is rarely what you want. The compiler warns if you hide a member without writing new.
In the .NET library
Interface members and abstract members are always dispatched on the object. Marking an override as sealed override stops further overriding below that class.