new keyword in method signature
See the question and my original answer on StackOverflowFWIW, I've been writing C# code for quite a time now, and the only case where I needed the new
keyword was the following OO hierarchy scenario:
public abstract class Animal
{
protected Animal(Animal mother, Animal father)
{
Mother = mother;
Father = father;
}
public Animal Mother { get; }
public Animal Father { get; }
}
public class Dog : Animal
{
public Dog(Dog mother, Dog father)
: base(mother, father)
{
}
public new Dog Mother => (Dog)base.Mother;
public new Dog Father => (Dog)base.Father;
}
Few remarks:
- No OO rule is broken, base classes still work fine.
- Properties are not marked
virtual
on purpose, they don't need to be. - In fact we enforce more OO rules thanks to the new keyword: a dog cannot have any animal as a father/mother. It must be a dog.
- the
new
keyword is used because we cannot "override" a property (or method) just by changing its return type.new
is the only way to have a nice OO hierarchy.