The best example for when to use
new keyword with function (i.e. new modifier):
You can use it to imitate return type covariance.
abstract class Enclosure
{
protected abstract Animal GetContents();
public Animal Contents() { return this.GetContents(); }
}
class Aquarium : Enclosure
{
public new Fish Contents() { ... }
protected override Animal GetContents() { return this.Contents(); }
}
This is a work-around. public Fish Contents() { ... } is not legal, despite being safe.
In general, you should not use method hiding, as it is confusing to consumers of your class (the specific example above does not suffer from this problem). Just name your new method something else if you don't want to override an existing method.
A likely real-world situation where you would need method hiding is if the provider of a base class added a generic method which you had already added to a derived class. Such a program will compile (and give warnings) without the new keyword, but adding new says, "I know my version of this method is replacing the base class's version. This is horrible and confusing, but we're stuck with it." That's still better than forcing the derived class to rename their method.
Just allowing the derived method to be treated as being an override would cause problems. Ignoring any concerns with implementing the compiler, the new method is semantically different from the base method, but polymorphism would cause the new method to be called when asked to call a method with the same name.
Note:
1) New methods are expected to hide base methods. The new modifier specifies that a method is supposed to hide a base method. It eliminates a warning issued by the compiler. No functionality is changed. But an annoying warning is silenced.
2) Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.
3) In some scenarios the new keyword prevents a warning from the C# compiler.
References:
http://blogs.msdn.com/b/ericlippert/archive/2004/01/07/virtual-methods-and-brittle-base-classes.aspx
http://shivasoft.in/blog/microsoft/csharp/virtual-override-and-new-keyword-in-c/
Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif
Programmer123, if this helps please login to Mark As Answer. | Alert Moderator