Given the following classes:
ClassA
{
public ClassA DoSomethingAndReturnNewObject()
{}
}
ClassB : ClassA
{}
ClassC : ClassA
{}
Is there a way to get ClassB
and ClassC
to inherit the method but customize the return type to their own class?
I prefer not to copy the method from ClassA and change the type there.
I need to get a ClassB
object when I call ClassB.DoSomethingAndReturnNewObject()
.
I need to get a ClassC
object when I call ClassC.DoSomethingAndReturnNewObject()
.
Something like calling a constructor based on current type like: this.GetType()
? But I have no clue how to actually do that.
You need to create a protected virtual method for the DoSomethingAndReturnNewObject
to use:
class ClassA
{
protected virtual ClassA Create()
{
return new ClassA()
}
public ClassA DoSomethingAndReturnNewObject()
{
ClassA result = Create();
// Do stuff to result
return result;
}
}
class ClassB : ClassA
{
protected override ClassA Create() { return new ClassB(); }
}
class ClassC : ClassA
{
protected override ClassA Create() { return new ClassC(); }
}
Note the return type remains ClassA but the object instance type will be the specific class.
What you're describing is a covariant return type and is not supported in C#.
However, you could create ClassA as an open generic and have the closed generic inheritors return their own type.
Example:
public abstract class ClassA<T> where T: ClassA<T>, new()
{
public abstract T DoSomethingAndReturnNewObject();
}
public class ClassB: ClassA<ClassB>
{
public override ClassB DoSomethingAndReturnNewObject()
{
//do whatever
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With