Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there ever a reason to hide inherited members in an interface?

I understand that a class which inherits from another class may hide a property by using the new keyword. This, however, is hiding a specific implementation of the property, so I can see how it could be used.

Is there any practical reason to hide members in interfaces which implement other interfaces? For example consider the example below. IChildInterface implements IParentInterface, and hides PropertyA.

interface IParentInterface
{
    string Name { get; set; }
    int PropertyA { get; set; }
    int PropertyB { get; set; }
}

interface IChildInterface : IParentInterface
{
    int PropertyA { get; set; }
    int PropertyC { get; set; }
}
like image 687
Eric Anastas Avatar asked Aug 25 '10 21:08

Eric Anastas


1 Answers

Is there any practical reason to hide members in interfaces which implement other interfaces?

Sure. The fact that the BCL itself uses this pattern is indicative that the pattern is practical. For example:

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

The designers of IEnumerable<T> wished to be backwards-compatible with IEnumerable but also wanted to ensure that every usage of GetEnumerator on the generic interface called the generic version. Hiding is the appropriate mechanism in this case.

For some additional discussion on subtle points about method hiding, see:

http://blogs.msdn.com/b/ericlippert/archive/2008/05/21/method-hiding-apologia.aspx

like image 76
Eric Lippert Avatar answered Oct 24 '22 19:10

Eric Lippert