Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 589
Dhwani Avatar asked Mar 16 '13 13:03

Dhwani


People also ask

How can I instantiate a class by name?

Instantiating a Class The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object. The new operator returns a reference to the object it created.

How do I create an instance of a class in C#?

You declare an instance constructor to specify the code that is executed when you create a new instance of a type with the new expression. To initialize a static class or static variables in a non-static class, you can define a static constructor.


3 Answers

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.

like image 159
Display Name Avatar answered Sep 28 '22 12:09

Display Name


    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

like image 27
Avinash Avatar answered Sep 28 '22 12:09

Avinash


the easiest way is to use Activator. Pass class name to GetType and Create new instance.

ClassInstance s1 = (ClassInstance)Activator.CreateInstance(Type.GetType("App.ClassInstance"));

public class ClassInstance
{
    public string StringData { get; set; }
}

Regards, Nik

like image 26
Nik Avatar answered Sep 28 '22 14:09

Nik