Home   Cover Cover Cover Cover
 

Hiding methods

Question: To deal with the fragile base class problem, C# provides the new keyword to hide inherited methods in the subclass. What would the alternative be to hiding these methods? What would be the advantages and disadvantages?

Answer:If a base class introduces a method M, which already exists in a subclass, C# requires that M is declared with new in the subclass. This makes it explicit that the M method in the subclass is not intended to override the M method of the base class but rather hides it (i.e. redeclares it).

As an alternative the name of the M method in the subclass could be changed to M1. This too would make it clear that M1 does not override M.

The benefit of this alternative would be that the complex mechanism of hiding is not necessary. Dynamic binding would be much easier to understand, because any method call obj.M would simply call the M method of obj's dynamic type.

The disadvantage would be that it could be complicated (if not impossible) to change M to M1 because too many programs might have to be changed. Furthermore, the M method from the base class would still be visible in the subclass, which might not be desirable.