- 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.
So by using this method we will create the object to any class. Here I will create the object to both class like this.
- T obj=new T();
- T GetObject < T > (params object[] lstArgument)
- {
- return (T) Activator.CreateInstance(typeof (T), lstArgument);
- }
- // Create object with default parameter.
- 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);
- // Create object with argumented parameter.
- 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.

Santhakumar MunuswamyPosted Jan 10, 2016, 12:05 PM
Thanks for nice share