C# – Practical Uses of the ‘New’ Modifier for Hiding

ckeywords

A co-worker and I were looking at the behavior of the new keyword in C# as it applies to the concept of hiding. From the documentation:

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.

We've read the documentation, and we understand what it basically does and how it does it. What we couldn't really get a handle on is why you would need to do it in the first place. The modifier has been there since 2003, and we've both been working with .Net for longer than that and it's never come up.

When would this behavior be necessary in a practical sense (e.g.: as applied to a business case)? Is this a feature that has outlived its usefulness or is what it does simply uncommon enough in what we do (specifically we do web forms and MVC applications and some small factor WinForms and WPF)? In trying this keyword out and playing with it we found some behaviors that it allows that seem a little hazardous if misused.

This sounds a little open-ended, but we're looking for a specific use case that can be applied to a business application that finds this particular tool useful.

Best Answer

You can use it to imitate return type covariance (Note: After this answer was written, C# 9.0 added support for return type covariance). Eric Lippert's Explanation . Eric provides this example code:

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 override 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.

This situation is discussed in detail in this post by Eric Lippert.

Related Topic