23

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.

3

5 Answers 5

25

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.

2
  • 1
    +1 for new being a marker for "this is horrible and confusing". Commented Aug 10, 2012 at 6:32
  • I think Eric's example is very helpful, if only because I am in a similar situation ... I have a base class implementing a nontrivial method that returns TBase, and a derived class that should return a TDerived. In this case, it feels like a necessary evil.
    – Kyle Baran
    Commented Jun 27, 2014 at 23:45
4

I think it is there in case you might need it to do something the language designers might not have thought of. C# was in many ways a reaction to early versions of java. And one thing java did was to very explicitly pigeonhole developers to eliminate possiblities of developers shooting themselves in the feet. C# took a slightly different approach and gave developers a bit more power at allowing developers a few more opportunities to shoot themselves in the feet. One example is the unsafe keyword. This new keyword is another.

Now, it probably isn't as useful as unsafe but once you get into a language spec it is hard to get out of a language spec.

1
  • 5
    Java does not have new because Java treats all methods as virtual. According to Eric Lippert, the motivation for supporting new is to solve the brittle base class problem. The existence of new is necessary for real-world business use, not just for low-level library use. Java not having new (and not having non-virtual methods) means that if a base class introduces a new method which is already in use within derived classes, existing code may break, despite the fact that the developer of the base class should be permitted to be oblivious to code which consumes it.
    – Brian
    Commented Jun 21, 2012 at 14:47
3

It's telling the reader that "I deliberately hid the base class' implementation of this method", as opposed to accidentally.

1
  • 6
    This strikes me as begging the question. The OP knows what it does but wants to know why.
    – Brian
    Commented Jun 21, 2012 at 13:25
0

You may want to have the previous member available thru other name:

class VehicleClass
{
  public int AnyProperty
  {
    get; set;
  }

  public int AnyFunction() { return 0; }
} // VehicleClass

class IntermediateClass : VehicleClass
{
  public int PreviousAnyProperty
  {
    get { return AnyProperty; }
    set { AnyProperty = value  }
  }

  public int PreviousAnyFunction() { return AnyFunction(); }
} // IntermediateClass 

class CarClass : IntermediateClass
{
  public new int AnyProperty
  {
    get ; set ;
  }

  public new int AnyFunction() { return 5; }
} // class CarClass

class ExampleClass
{

  public static void Main()
  {
    using (CarClass MyCar = new CarClass())
    {
      int AnyInt1 = MyCar.PreviousAnyProperty;
      MyCar.PreviousAnyProperty = 7;

      int AnyInt2 = MyCar.PreviousAnyFunction();

      int AnyInt3 = MyCar.AnyProperty;
      MyCar.AnyProperty = 45;

      int AnyInt4 = MyCar.AnyFunction();
    }
  } // static void Main()

} // class CarClass

Cheers.

2
  • I'm familiar with how it works, but my question truly is Why would you want to have the previous member available through another name? This breaks all kinds of contracts, renders certain generic pieces useless. Commented Jun 21, 2012 at 17:50
  • @Joel Etherton: As you may alredy know, sometimes developers have to "pick" others people programming code. And we may not authorized to modify, maybe extend classes. And may require to use both, the previous member & the new one.
    – umlcat
    Commented Jun 21, 2012 at 18:08
0

I have found it quite useful when creating a test suite for legacy code. It enables me to hide external dependencies, like querying a database inside a method that is used by other methods. To be able to test the other methods I can hide the original logic that depends on external resources without needing to add the virtual keyword to those methods in test classes.

Not the answer you're looking for? Browse other questions tagged or ask your own question.