Create object instance of a class having its name in string variable

Having the class name in string is not enough to be able to create its instance. As a matter of fact you will need full namespace including class name to create an object.

Assuming you have the following:

string className = "MyClass";
string namespaceName = "MyNamespace.MyInternalNamespace";

Than you you can create an instance of that class, the object of class MyNamespace.MyInternalNamespace.MyClass using either of the following techniques:

var myObj = Activator.CreateInstance(namespaceName, className);

or this:

var myObj = Activator.CreateInstance(Type.GetType(namespaceName + "." + className));

Hope this helps, please let me know if not.


    string frmName = "frmCustomer";
    //WorldCarUI. is the namespace of the form
    Type CAType = Type.GetType("WorldCarUI." + frmName );
    var myObj = Activator.CreateInstance(CAType);
    Form nextForm2 = (Form)myObj;
    nextForm2.Show();

this does works..

Regards Avi