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
Derived
is a subtype ofBase
, then any code depending onBase
(e.g, a method with aBase
parameter, 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
Derived
to aBase
variable, theBase
implementation will be called.That's the expected behaviour, since
Say
is not virtual. This means that code written against aBase
variable, expects theBase
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.