Reputation: 37115
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.
Upvotes: 1
Views: 81
Reputation: 876
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.
Upvotes: 0
Reputation: 2652
Interfaces have no inheritance or an idea of overwriting something. All you avoid here with the "new" is a Name Conflict. You implement a new Property, with incidently the same name. Everything else will work as usually.
When implementing IBar on a class, you have the possibility of defining a public property, this will serve as both Name properties. The algorithm of implicitly defining an interface works from the view of the Interface. The C# compiler searches for a property name 'Name' for IFoo and it searches again for IBar, and suddenly finds the same property for both.
Alternativly you declare the interface members explicitly, and you can attach two different implementations of 'Name', if you like.
This explains also why you always have to name the Explicit definition with it's defining type. You have to Implement explictly IFoo.Name and IBar.Name, it's not hidden in any way, it can be both access from outside, depending on what Cast to what interface you are using. It's like you define the a class "Name" in two different namespaces, same idea here.
You would less likely come up with this question in VB.Net, cause there every interface implementation is explicit.
Upvotes: 1