Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is method hiding ever a good idea

Tags:

c#

oop

In C# the new modifier can be used to hide a base class method without overriding the base class method.

I've never encountered a situation where hiding a method was the best choice available. Are there any situations where method hiding is the best choice?

like image 556
ScottS Avatar asked Apr 18 '10 17:04

ScottS


People also ask

Why do we need method hiding?

In method hiding, you can hide the implementation of the methods of a base class from the derived class using the new keyword. Or in other words, in method hiding, you can redefine the method of the base class in the derived class by using the new keyword.

Why should we use method hiding in C#?

It tells us to use the new keyword to hide the inherited member. So, by using the new modifier in the derived class method, it hides the implementation of the base class method. This is called Method Hiding. It allows you to provide a new implementation for a derived class.


1 Answers

There are rare, but very good, reasons to use method hiding. Eric Lippert posted a great example on his blog:

interface IEnumerable<T> : IEnumerable {    new IEnumerator<T> GetEnumerator();  } 

However, I think hiding should be the exception, and only used sparingly.

like image 170
Reed Copsey Avatar answered Oct 06 '22 17:10

Reed Copsey