Create object instance of a class from 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.

Leave a Comment