Given the following client code:
var obj = new Class1();
Is there any way to modify the constructor of Class1 so that it will actually return a subclass (or some other alternate implementation) instead?
I would like obj to get one of two different implementations, depending on some condition. Obviously, I could change to using a factory or DI framework, but I'd like to avoid changing the client code, if possible.
I assume the answer is no, but I wonder if there's some clever way of making that happen.
You can replace the constructor with a factory method, and return whatever you like, depending on the parameters:
public Class2 : Class1 {}
public static Class1 CreateClass1(bool returnDerivedClass)
{
if (returnDerivedClass)
{
return new Class2();
}
else
{
return new Class1();
}
}
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