Are there situations where you need to use the new instead of overriding when managing the base class?

The examples I came across when “new” makes sense are related to maintenance situations, when a subclass is inherited from the base class in the library, and the new version of the library adds a method with the same name as the one that was implemented in the subclass. (See: Fragile Base Classes )

I am wondering if there are times when using the “new” is a good design choice (and not something that may be required during maintenance). One thing that cannot be done when overriding is to change the return type of the method / property, keeping the name the same, but I doubt if it has ever been a good design choice.

public class FruitBasket {
    public int Weight { get; set;}
    public List<Fruit> Fruits {get; set;}
}

public class AppleBasket : FruitBasket {
    public new List<Apple> Fruits  {get; set;}
}
+5
source share
2 answers

One of the situations that I know of is that you should use new ones in .Net WinForms if you bind to an interface that inherits from another interface and you want to bind to elements in the base interface.

For example, if you have

public interface IOne
{
   int ID {get;set;}
   string Code {get;set;}
}

public interface ITwo : IOne
{
   DateTime CreatedDate {get;set;}
}

and you bind the control to an ITwo object, then you cannot see the properties of the ID or code unless you add them to the ITwo interface. Of course, you do not need to use new ones, but it is recommended.

In addition, I used it only in maintenance mode, i.e. after sending the application, and new requirements require such a change.

NTN, Dean.

0
source

, MSDN , new : ( MSDN: ). , .

-1

All Articles