Search code examples
c#interfacemember-hiding

Hiding interface-member in derived interface


I just decompiled some 3rd-party interface and scratched my head about the following:

public interface IFoo 
{
    string Name { get; set; }
}
public interface IBar : IFoo
{
    new string Name { get; set; }
}

As you can see I have two interfaces, where IBar extends IFoo by hiding its Name-property. However I can´t see what the new-keyword is doing here. I read an answer from Eric Lippert that relates to members that solely differ on their return-type. However in my case everything is just a string.

Of course we could explicitely implement either of the interfaces. But that would be possible without new anyway.


Solution

  • Name field in IFoo and IBar are different, you can implement two Name in a class:

    public interface IFoo
    {
        string Name { get; set; }
    }
    public interface IBar : IFoo
    {
        new string Name { get; set; }
    }
    
    public class Implementation : IBar
    {
        string IBar.Name { get; set; } = "Bar";
    
        string IFoo.Name { get; set; } = "Foo";
    }
    

    If you cast Implementation class to IBar, the value will be Bar and if you cast it to IFoo, the value will be Foo.