I have a subclass with an over-ridden method that I know always returns a particular subtype of the return type declared in the base class. If I write the code this way, it won’t compile. Since that probably doesn’t make sense, let me give a code example:
class BaseReturnType { } class DerivedReturnType : BaseReturnType { } abstract class BaseClass { public abstract BaseReturnType PolymorphicMethod(); } class DerivedClass : BaseClass { // Compile Error: return type must be 'BaseReturnType' to match // overridden member 'BaseClass.PolymorphicMethod()' public override DerivedReturnType PolymorphicMethod() { return new DerivedReturnType(); } }
Is there any way to accomplish this in C#? If not, what’s the best way to achieve something similar? And why isn’t it allowed? It doesn’t seem to allow any logical inconsistency, since any object returned from the over-ridden method still is BaseReturnType. Maybe there is something I hadn’t considered though. Or maybe the reason is technological or historical.
Unfortunately no, covariant return types aren’t supported in C# for method overriding. (Ditto contravariant parameter types.)
If you’re implementing an interface you can implement it explicitly with the ‘weak’ version and also provide a public version with the stronger contract. For simple overriding of a parent class, you don’t have this luxury I’m afraid 🙁
(EDIT: Marc has a reasonable solution – although it’s pretty ugly, and method hiding is generally a bad thing for readability. No offence meant, Marc 😉
I believe this is actually a CLR restriction, not just a language one – but I could well be wrong.
(As a matter of history, Java (the language) had the same restriction until 1.5 – but it gained covariance at the same time as generics.)