Given the following code:
public interface IFoo {}
public interface IBar
{
IFoo MyMethod();
}
public abstract class MyClass<T> : IBar where T : IFoo
{
public abstract T MyMethod();
}
Why am I receiving the error MyClass<T> does not implement interface member IBar.MyMethod(). MyClass<T>.MyMethod() cannot implement IBar.MyMethod() because it does not have the matching return type of IFoo.
?
I added the constraint where T : IFoo
, so I would have expected T and IFoo to be interchangeable.
The reason is because the C# specification states that:
For purposes of interface mapping, a class or struct member
A
matches an interface memberB
when:
A
andB
are methods, and the name, type, and formal parameter lists ofA
andB
are identical.
So the return types must be identical.
The feature of allowing covariant returns of interface implementations was proposed once: The proposal. It is also mentioned that this change will cause the code not to be forward compatible, therefore it may be declined, and finally it was really declined.
Due to this breaking change, we might consider not supporting covariant return types on implicit implementations.