I was wondering if there are any (runtime) difference if I implement an interface on a derived class if the base abstract class implements it already abstract:
public interface IFoo
{
void Bar();
}
public abstract class Base : IFoo
{
public abstract void Bar();
}
public class Derived : Base, IFoo // does this make any difference?
{
public override void Bar()
{
// do something
}
}
Is there any difference writing the "implemention" IFoo
on Derived
for example when I check if an instance implements an interface at runtime etc.?
Consider following on your example. Must the following be possible?
void f(Base b){
IFoo ifoo = b;
}
Because an object b is a Base, it must be an IFoo because Base implements IFoo. Now consider the following.
var d = new Derived();
f(d);
Since d is a Derived, it is a Base, because derived inherits from Base. Because of this, we can pass it to f, where it is then assigned to an IFoo, as we did before.
Essentially, because a derived class still is also all of its base classes, it already implements all of its base classes' interfaces. The designers of the language acknowledged this and there is no need to redeclare that a derived class is implementing interfaces that are implemented by its base classes.
I guess that maybe your question arises because of where you actually put the method body, but that really isn't relevant. The declaration of the interface is a contract for other consumers of objects of that type. Those consumers don't care where the method body was defined, all that they care is that when they have an IFoo, that it has a method with the signature void Bar()
that can be called, as I showed earlier, inheritance must include all interfaces, so there is no need to declare them again.