How do I instantiate a class given its string name?

ctrlShiftBryan picture ctrlShiftBryan · Feb 11, 2010 · Viewed 58.5k times · Source

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?

Answer

Seth Petry-Johnson picture Seth Petry-Johnson · Feb 11, 2010

Look at Activator.CreateInstance().

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

or

var type = Type.GetType("MyFullyQualifiedTypeName");
var myObject = (MyAbstractClass)Activator.CreateInstance(type);