Here I will go to explain about how to create the object to generic or unknown class. This situation we will get in the most of the situation. Mostly this will useful to develop the independent component development. So we will see through the sample. Create three different classes like below code:
- public class Employee
- {
- public string Name
- {
- get;
- set;
- }
- public string Address
- {
- get;
- set;
- }
- }
- public class Student
- {
- public string Name
- {
- get;
- set;
- }
- public string Department
- {
- get;
- set;
- }
- public Student(string name, string department)
- {
- this.Name = name;
- this.Department = department;
- }
- }
These two classes are totally different type and the constructor also different. Here I will go to create the object to these two classes by using one generic method. Generally we can’t able to create the object to generic type like:
It will throw the exception. But we will get the type of generic type by using typeof operator. So here I go to use the typeof operator. If we know the type, we will easily create the object by using Activator class located in the System namespace. The below code show you to how to do this.
- T GetObject < T > (params object[] lstArgument)
- {
- return (T) Activator.CreateInstance(typeof (T), lstArgument);
- }
So by using this method we will create the object to any class. Here I will create the object to both class like this.
-
- Employee emp = GetObject < Employee > ();
- emp.Name = "Sakthikumar";
- emp.Address = "Chennai";
- Console.WriteLine("Employee Detail");
- Console.WriteLine("----------------");
- Console.WriteLine("Name : " + emp.Name);
- Console.WriteLine("Address : " + emp.Address);
-
- Student student = GetObject < Student > ("Sakthikumar", "MCA");;
- Console.WriteLine("Student Detail");
- Console.WriteLine("----------------");
- Console.WriteLine("Name : " + emp.Name);
- Console.WriteLine("Department : " + emp.Address);
Please feel free if you have any doubt regarding this.