jmayor
jmayor

Reputation: 2795

New and Virtual operators in C#

Is it alright in a hierarchy to use the new keyword at some point to override the return type in a method?

Can I use virtual new or new virtual so I can override the return type?

I need to consider also classes that inherit from that point on. Can they override this method where the base was created with new?

Upvotes: 1

Views: 287

Answers (2)

Travis Heseman
Travis Heseman

Reputation: 11449

Hypothetically....

public class BaseCollection<T>
{
  // void return - doesn't seem to care about notifying the 
  // client where the item was added; it has an IndexOf method 
  // the caller can use if wants that information
  public virtual void Add(T item)
  {
    // adds the item somewhere, doesn't say where
  }

  public int IndexOf(T item)
  {
     // tells where the item is
  }
}

public class List<T> : BaseCollection<T>
{
  // here we have an Int32 return because our List is friendly 
  // and will tell the caller where the item was added
  new public virtual int Add(T item) // <-- clearly not an override
  {
     base.Add(item);
     return base.IndexOf(item);
  }
}

Here I use the "new" modifier because a List<T> reference will hide the Add method from the BaseCollection<T>. By default, hiding members from a base generates a warning from the compiler (an error if you have compilation set up to fail on warnings). So I'm basically telling the compiler... "Yeah I know I hid the Add method with the void return, it's desired functionality - just go with it."

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564333

You can do this, but the real question is whether you should do it.

The problem is that you'll get very unexpected behavior, depending on how your class is used. If you're calling your class from an instance of the base class, the original, non-"new" method will get called, which will probably be unexpected.

In general, I'd avoid using the new keyword to override a base class method unless there is a very distinct reason to do so - if your method is going to return a new type, declare it as a new method with a different name or signature instead of hiding the base class method - it will make your hierarchy much more usable.

Upvotes: 14

Related Questions