Given these declarations:
public interface I
{
void M() => Console.WriteLine("I.M");
}
public class C0 : I
{
public void M() => Console.WriteLine("C0.M");
}
public class C1 : I
{
}
public class D1a : C1
{
public void M() => Console.WriteLine("D1a.M");
}
public class D1b : C1, I
{
public void M() => Console.WriteLine("D1b.M");
}
these statements:
I c0 = new C0();
I c1 = new C1();
I d1a = new D1a();
I d1b = new D1b();
c0.M();
c1.M();
d1a.M();
d1b.M();
produce this output:
C0.M
I.M
I.M
D1b.M
I understand the behaviour of C0
and C1
, but why does the method implementation in D1a
not replace the default implementation from the interface? Why does adding the otherwise redundant interface declaration to D1b
resolve the issue?
It has been suggested that this question is a duplicate. I have found no other questions on SO addressing this particular scenario.
Generally a derived class does not need to declare that it implements an interface that is implemented by a base class.
The question here is, why, in the case of being able to override a default member implementation in an interface, does the derived type need to redeclare the interface?
I understand the behaviour of C0 and C1, but why does the method implementation in D1a not replace the default implementation from the interface?
In this case what is happening is that your class C1
is creating a somewhat hidden method M()
by means of an explicit implementation of the interface using the default implementation. This is equivalent to the following:
public class C1 : I
{
void I.M() => Console.WriteLine("C0.M");
}
Notice if you try to call that method from C1 casted as a C1, you cannot call it:
Thus, when you add a new method in the new derived class, that method is not actually implementing the interface but is truly a new method.
Why does adding the otherwise redundant interface declaration to D1b resolve the issue?
Adding the explicit interface implementation to that class overrides the default implementation of the interface, because you are now actually creating a new implmenetation of that interface for that object.
Here are a couple links to Microsoft's documentation for further details: