My code is using a list with baseclasses that i later cast into their respective derived types. I hit a point where I thought I could create a constructor for the baseclass that would figure out of what type it should be and change itself into that type. Something like this:
public class BaseClass
{
// Constructor
BaseClass(string Input)
{
if (Input.Substring(0, 5) == "Something")
return new DerivedClass(); // <-- Not allowed
}
}
public class DerivedClass : BaseClass
{
}
This isn’t allowed since a constructor must return void. Changing type of “this” doesn’t seem to be allowed either. I know that there are very simple alternatives to this code that works, but I think that it has a certain elegance to it, don’t you think?
You should look into the Factory Pattern. It is used when you want to create an instance of an object but allow the specific type to be determined based on other parameters.