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

.net, c#, reflection, runtime, system.reflection

Solution

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.

Problem

I don't know whether this is possible or not, but I would like to know if it is and, if so, how it works. So here is my question: I have 2-3 custom model classes of my own. For example, `Customer`, `Employee` and `Product`. I also have a class name in a string. Based on the class name, I want to create an instance and return it to a view. How can I achieve this? I know that one option is an `if/else` statement, but I would like a better, dynamic way.

Original source