Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can A Constructor Return a SubClass?

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.

like image 586
rjw Avatar asked Feb 28 '10 19:02

rjw


1 Answers

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();
    }
}
like image 96
John Saunders Avatar answered Sep 16 '22 18:09

John Saunders