I essentially define IFoo
twice in the Inherited class. Does that cause some unforeseen consequences?
interface IFoo {
...
}
interface IBar : IFoo {
...
}
class Base : IFoo {
...
}
class Derived : Base, IBar {
...
}
The reason I want to make IBar
inherit from IFoo
is so I can work on Derived
as it was IFoo
without having to cast it.
if (Derived is IBar)
// Do work
If it doesn't inherit I have to cast it. Which makes use more complicated, and users of the class might not understand that IBar
just is a specialization of IFoo
.
if (Derived is IBar)
Derived as IFoo
// Do work
Is this bad practice? What other solutions are there to this problem?
Simply put, in Java, a class can inherit another class and multiple interfaces, while an interface can inherit other interfaces.
In Multiple inheritance, one class can have more than one superclass and inherit features from all its parent classes. As shown in the below diagram, class C inherits the features of class A and B. But C# does not support multiple class inheritance.
A class or struct can implement multiple interfaces, but a class can only inherit from a single class.
No you cannot inherit multiple interfaces, because interfaces cannot be inherited. Interfaces are IMPLEMENTED, not inherited.
It will not cause any unforeseen circumstances in code terms. It's just redundant.
As for this code:
if (Derived is IBar)
Derived as IFoo
That's completely unnecessary since Derived
is an IFoo
, given your declarations - so don't do that!
Note that even if IBar
doesn't derive from IFoo
, you still don't need Derived as IFoo
. Given:
interface IFoo {}
interface IBar {}
class Base : IFoo {}
class Derived : Base, IBar
{
}
Then this compiles ok:
var derived = new Derived();
IBar bar = derived; // Fine.
IFoo foo = derived; // Also fine.
If I understand you correctly, you have one hierarchy of interfaces and one hierarchy of classes mirroring each other. Each class implements the corresponding interface by inheriting from it's base class and implementing the additional members needed.
This is just fine and I do it the same way. I don't know any better way to do this - this is a good approach.
I think IBar should extend IFoo just like your main suggestion, otherwise consumers would need to cast a lot. Also, since you consider IBar a specialization of IFoo, also make it a specialization in the code, so make it extend IFoo.
You can explicitly define an implementation for an Interface
and so distinguish in behavior
class Derived : Base, IBar {
void IBar.Method(){
}
void Base.Method() {
}
}
Apart from that, you can do that, but it is redundant and might cause confusion. See MSDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With