My subclasses don’t appear to be able to masquerade as the base class when satisfying interface requirements. For example:
class MyBaseClass
{}
class MySubClass : MyBaseClass
{}
interface MyInterface
{
MyBaseClass someFunction();
}
class MyImplementation : MyInterface
{
public MySubClass someFunction() { return null; }
}
Generates the following error:
‘MyNamespace.MyImplementation’ does not implement interface member ‘MyNamespace.MyInterface.someFunction()’. ‘MyNamespace.MyImplementation.someFunction()’ cannot implement ‘MyNamespace.MyInterface.someFunction()’ because it does not have the matching return type of ‘MyNamespace.MyBaseClass’.
This is also a problem with requiring interfaces vs. implementations. For example, if I have an interface with a function that returns an IList my implementation cannot return a List – it MUST return an IList.
Am I doing something wrong or is this a limitation of C# interfaces?
C# doesn’t support covariant return types. When implementing an interface, you have to return the type specified by the interface. If you want to, you can explicitly implement the interface and have another method with the same name that returns the subtype. For example: