Given the following classes:
ClassA
{
public ClassA DoSomethingAndReturnNewObject()
{}
}
ClassB : ClassA
{}
ClassC : ClassA
{}
I think that you need to create a new function with the new return type and call inside the other function, and manipulate the type returned. otherwise it will no be logical ! (with the definition/idea of inheritance)
There's one really simply answer: make all the method return types "object". You're obviously returning different types, strings and ints and whatnots, and they will stay what they are after they reach their destination. But the compiler is perfectly happy - everything's an "object". You do give up compile-time type-checking, not a good thing, but every once in a while for some deep OO programming the return is worth it.
This isn't inheritance, because the return type of the method is part of its signature. You're not changing the method, you'd be creating an entirely new one.
You do have some options. You could, for example, make the method DoSomethingAndReturnNewObject
a generic-based method, and have it return its generic type. This is probably the most direct path to the exact behavior for which you're looking.
The other alternative is to leave the method signatures as-is, and have the subclass methods return instances of ClassB
and ClassC
. Then the client code would need to be responsible for casting in order to use those objects as their appropriate derived classes.
Is there some reason the common interface of ClassA
doesn't suffice? Polymorphism will, if you have derived and overridden virtual members correctly, provide you with the correct functionality if you're only using the ClassA
members.
No, the feature you mentioned is called return type covariance. It's not supported in C#.