Search code examples
c#oopnew-operatorliskov-substitution-principle

Member hiding, what is its practical purpose


What is the actual practical use of the 'new' modifier?

public class Base
{
    public void Say()
    {
        Console.WriteLine("Base");
    }
}

public class Derived:Base
{
    public new void Say()
    {
        Console.WriteLine("Derived");
    }
}

It wouldn't it better if this just fails to compile? This code:

        Derived d = new Derived();
        d.Say();
        ((Base)d).Say();

Returns

 Derived
 Base

Doesn't this break the Liskov substitution principle?

Cheers.


Solution

  • Regarding LSP

    That doesn't break the LSP. The LSP states that if Derived is a subtype of Base, then any code depending on Base (e.g, a method with a Base parameter, like void DoSomething(Base b)) can be replaced with an instance of Derived, without any surprising effects.

    And as you pointed out, if you assign an instance of Derived to a Base variable, the Base implementation will be called.

    That's the expected behaviour, since Say is not virtual. This means that code written against a Base variable, expects the Base implementation to be called.

    Practical purpose

    You can think of new methods as a way to circumvent a non-overridable method - with a caveat! You'll have to program against that specific type - not its interface.