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.
Regarding LSP
That doesn't break the LSP. The LSP states that if
Derivedis a subtype ofBase, then any code depending onBase(e.g, a method with aBaseparameter, likevoid DoSomething(Base b)) can be replaced with an instance ofDerived, without any surprising effects.And as you pointed out, if you assign an instance of
Derivedto aBasevariable, theBaseimplementation will be called.That's the expected behaviour, since
Sayis not virtual. This means that code written against aBasevariable, expects theBaseimplementation to be called.Practical purpose
You can think of
newmethods as a way to circumvent a non-overridable method - with a caveat! You'll have to program against that specific type - not its interface.