You can do it using reflection. Here is the idea: you get the type and inquire for its constructors. You need to know the purpose of each constructor in advance, so most usually this is done based on parameterless constructor, or some constructor signature you specifically design for this purpose. (Apparently, you want to do it for some set of types. If it was just one type, you would simply hard-code the construction of the object. So, you can create some constructor signature shared by all the types you want to instantiate programmatically and make sure all your types implement it.)
If you simply can use default constructor, you can call
System.Activator.CreateInstance
:
http://msdn.microsoft.com/en-us/library/wccyzw83.aspx[
^].
In more general case, you use one of the reflection methods named "GetConstructor" or "GetConstructors" to get and instance of the class
System.Reflection.ConstructorInfo
or array of such instances:
http://msdn.microsoft.com/en-us/library/system.type.aspx[
^],
http://msdn.microsoft.com/en-us/library/h93ya84h.aspx[
^].
If this is the array of
System.Reflection.ConstructorInfo
instances, you traverse this array to pick one you need, typically by finding out the one with the signature you need, which you can do looking at the list of parameters:
http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getparameters.aspx[
^].
When you found appropriate constructor, you use on of the invoke methods to create an object:
http://msdn.microsoft.com/en-us/library/6ycw1y17.aspx[
^],
http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx[
^],
http://msdn.microsoft.com/en-us/library/x7xy3xtx.aspx[
^],
http://msdn.microsoft.com/en-us/library/4k9x6bc0.aspx[
^].
And finally, to use the object as the object of required type, you will need to cast it to required type.
—SA