Method hiding with new

1 min read
On trails:CSOOPstep 5/6
A derived class can define a member with the same name as a member in its base class by using the new keyword. This hides the base class member rather than overriding it. If the method is called on a derived class instance through a base class reference, the base class’s method is called, not the new method in the derived class.

This is method hiding, not true polymorphismPolymorphismOne call, many behaviors, decided by the actual type at runtime.Opens in a new tab, and it can lead to confusion if the distinction isn’t well understood. Using new can be a signal that the derived class method is intentionally different, and not a polymorphic substitute. That can break the Liskov Substitution PrincipleLiskov Substitution PrincipleA subtype must be usable anywhere its base type is.Opens in a new tab if client code doesn’t handle it carefully.

Calling through the derived reference runs the new method. Calling through the base reference runs the base method.
C#
public class BaseClassWithNew{    public void DoWork() { Console.WriteLine("BaseClassWithNew DoWork"); }}public class DerivedClassWithNew : BaseClassWithNew{    public new void DoWork() { Console.WriteLine("DerivedClassWithNew DoWork (new)"); }} // Usage:// DerivedClassWithNew derivedObj = new DerivedClassWithNew();// derivedObj.DoWork(); // Calls DerivedClassWithNew.DoWork() // BaseClassWithNew baseRefToDerived = derivedObj;// baseRefToDerived.DoWork(); // Calls BaseClassWithNew.DoWork()

Sources