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...
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With