I have a base class which contains an abstract/MustInherit method. I want this method to return an instance of a class which implements a given interface.
When I come to implement the method in the derived class, I get a compiler error because the return types do not match (ie. in the abstract class, the return type is that of the interface, whereas in the derived class the return type is the class which implements the interface).
Can anyone clarify the underlying problem for me? I can’t quite get my head around what’s wrong. Especially given that the specified return type of the abstract method is an interface, which can’t be instantiated, so surely the method implementation must return an instance of class which implements the interface? Maybe I just can’t see the wood for the trees.
I can code around the issue by making the base class generic (and I can specify that T must implement my interface), then the abstract method would return an instance of T. I’m not sure about that solution though. It seems a bit of a hack, I don’t get why I can’t do it with straight inheritance.
Here is one way you could accomplish what you’re after:
The issue is that overridden methods are constrained to have the exact same signature as their base. Suppose you were to create a value type that implements
ISomethingand then specialized the override in Derived to return the value type. Now the overridden method is returning a value type that implements the interface, but, calling the method from the Base, you would expect to get a boxed value type of the form of the interface. If the Derived call returned an unboxed value when calling through the Base, the calling code would try to access it as if it were already boxed, causing a failure.