If the fact that the only way to do this is by using the new
keyword bothers you, then in my opinion you're thinking about interfaces wrong.
Sure, you could say that IInherited
"inherits from" IBase
; but what does that really mean? These are interfaces; they establish code contracts. By hiding the IBase.Property1
property with new string Property1 { get; set; }
, you are not shadowing any functionality. Thus the traditional reason that a lot of developers consider hiding to be a "bad" thing -- that it violates polymorphism -- is irrelevant in this case.
Ask yourself: what really matters when it comes to interfaces? They provide a guarantee of responding to certain method calls, right?
So, given the following two interfaces:
interface IBase
{
string Property1 { get; }
}
interface IInherited : IBase
{
new string Property1 { set; }
}
- If an object implements
IBase
, you can read its Property1
property.
- If an object implements
IInherited
, you can read its Property1
property (just as with an IBase
implementation), and you can also write to it.
Again, there's really nothing problematic here.