Is there a way to do something like this in c#? Consider the following example and assume that Child1, Child2, Child3 are all children of Parent –
class Class1
{
SomeObject< Parent > mSomeObject;
Class1()
{
if (condition1)
mSomeObject = new SomeObject<Child1>();
else if (condition2)
mSomeObject = new SomeObject<Child2>();
else if (condition3)
mSomeObject = new SomeObject<Child3>();
}
}
The idea is that that Class1 would have SomeObject as a member, but it is uncertain until runtime what generic form of SomeObject it should take. Any help would be appreciated. Thanks!
You should use interface based inheritance. This will allow child1, child2, and child3 to be polymorphic and take on the characteristics of the parent without the need for such guard logic. With the IF tests gone your code will be more readable and easier to modify later.
Here’s and example I just wrote with LINQPad to show this in action.
OUTPUT:
I prefer interface based inheritance as opposed to abstract classes as described by AllenG. Reasons such as multiple inheritance – a class can implement many interface but only inherit from 1 class.
Hope this helps…