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

Dhwani picture Dhwani · Mar 16, 2013 · Viewed 71.6k times · Source

I don't know the thing I am asking is available or not but I just want to know if it exists and how it works. So here is my question:

I have 2-3 custom model class of my own. For example, Customer, Employee and Product. Now I have class name in a string. and based on the class name coming in a string, I have to create its object and return to a VIEW. How could I achieve this?

I know a option of IF ELSE statement but I want to try a better,"Dynamic" way...

Answer

Display Name picture Display Name · Mar 16, 2013

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.