views:

178

answers:

2

I have an abstract class and I want to initalize it to a class that extends it.

I have the child classes name as a string.

Besides this...

String childClassString;
MyAbstractClass myObject;

if (childClassString = "myExtenedObjectA")
    myObject = new ExtenedObjectA();
if (childClassString = "myExtenedObjectB")
    myObject = new ExtenedObjectB();

How can I do this? Basically how do I get rid of the if statements here?

+10  A: 

Look at Activator.CreateInstance().

myObject = (MyAbstractClass)Activator.CreateInstance("AssemblyName", "TypeName");

or

var type = Type.GetType("MyFullyQualifiedTypeName");
var myObject = (MyAbstractClass)Activator.CreateInstance(type);
Seth Petry-Johnson
+1  A: 

I believe this should work:

myObject = (MyAbstractClass)Activator.CreateInstance(null, childClassString);

The null in the first parameter defaults to the current executing assembly. For more reference: MSDN

edit: forgot to cast to MyAbstractClass

dboarman