Reputation: 4749
This is more or less an exact duplicate of this post, but as I cannot edit it, I started this. Feel free to move something over and close this one.
Using method hiding with new seems like a dangerous feature, and given the discussion in the other thread, it seems it's not only I who have problems finding a valid use case for this. Any methods accepting Base won't use Derived's Method.
public class Base
{
public void Method()
{
Console.WriteLine("Base");
}
}
public class Derived : Base
{
public new void Method()
{
Console.WriteLine("Derived");
}
}
var derived = new Derived();
derived.Method(); // "Derived"
((Base)derived).Method(); // "Base"
So what are some valid use cases for new that is difficult to solve with other features?
Upvotes: 4
Views: 216
Reputation: 1500355
The idea is to avoid the brittle base class problem as far as possible.
Suppose you provide a library, and I derive from one of your classes. I create my own method, Foo()
, and call it appropriately. Fine.
Now you introduce a second version of your library, and you add the Foo()
method (with the same signature) to the base class. Now your code will call Foo()
, which has one particular meaning... and that may be a completely different meaning to my Foo()
method. The default behaviour (and the behaviour if you add the new
modifier) is for things to behave as they should: code which only knows about the base class will call your method - which is fine, as that's what they mean. Code which uses an expression which has a compile-time type of my derived class will use my method - and that's fine, as that's what they should mean as well. (Basically it can only be my code, because only my code knows about my class.)
It should usually be avoided - it can lead to subtle bugs where changing the compile-time type of the variable silently changes the behaviour... but it's present for that sort of situation. Basically, adding a method to a base class shouldn't break derived classes, as far as possible.
Upvotes: 4