I want to do this:
interface IBase
{
string Property1 { get; }
}
interface IInherited : IBase
{
string Property1 { get; set; }
}
So that IInherited
would have the inherited property Property1
with added functionality to allow set
.
Is that possible? What's the syntax?
EDIT: please notice I put the word "inherited" in bold face. I am asking specifically about inheriting the property, not hiding it behind a new one.
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 theIBase.Property1
property withnew 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:
IBase
, you can read itsProperty1
property.IInherited
, you can read itsProperty1
property (just as with anIBase
implementation), and you can also write to it.Again, there's really nothing problematic here.
You can either mark the property with the "new" keyword, or you can skip the inheritance:
Or:
Either way, this should work:
You may want to think hard before you make an inheritance chain for your interfaces, though. Who is going to see which interface? Would you need to cast to IInherited when passed an IBase? If so, can you be guaranteed that you can do that cast (if you allow user created classes, then the answer is no)? This kind of inheritance can really hurt (re)usability if you're not careful.
Your code should work anyway... it just creates a complier warning because of hiding Property1. To clear this warning mark Property1 in IInherited with the new prefix
Hiding a member is violating the Liskov Substitution Principle and pretty much just shouldn't be done, ever. By hiding this member you are introducing a very difficult to locate bug since 2 different outcomes will occur depending whether you cast the object as IBase1 or cast it to IBase.
http://en.wikipedia.org/wiki/Liskov_substitution_principle
Unfortunately not - properties cannot be extended as such. However, you can just hide the property by using new:
Or, you can make your own getter and setter methods which can be overriden (good 'ol Java style):
Properties are actually converted to getter and setter methods by the compiler.
Not explicitly, no. You have two options:
Or you can just kill the compiler warning with the
new
keyword:Unless you implement
IInherited.Property1
explicitly,IBase
will bind to your settable implementation automatically.