tags:

views:

98

answers:

2

I have an abstract class Step, and many descendant Step classes that I would like to instantiate based on an XML document.

As such I would like to create an instance of a particular step class based on the type in the XML document

Step type="GenerateReport" .... Step type="PrintReport" ....

How can I instantiate an object by specifying the classname (and ideally the parameters to be passed through to the constructor)?

+6  A: 

I think you simply want to use the Activator.CreateInstance method:

var object = Activator.CreateInstance(null, "Classname");
Noldorin
+5  A: 

The easiest option is the Activator.CreateInstance overload that accepts a Type and a params object[]. For the Type, you can sometimes use Type.GetType(string), but this doesn't check all assemblies (just the current assembly and some system assemblies). If the name is assembly-qualified you'll probably be OK - but if it is just namespace-qualified (i.e. FullName) then you'll probably want to use Assembly.GetType(string) - i.e.

Type type = typeof(SomeKnownTypeInTheSameAssembly).GetType(fullName);
object obj = Activator.CreateInstance(type, args);
Marc Gravell
Thanks for the detailed answer - this worked a treat.
Alan Wolman