Create Object to Generic or Unknown Class

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:

  1. public class Employee  
  2. {  
  3.     public string Name  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string Address  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13. }  
  14. public class Student  
  15. {  
  16.     public string Name  
  17.     {  
  18.         get;  
  19.         set;  
  20.     }  
  21.     public string Department  
  22.     {  
  23.         get;  
  24.         set;  
  25.     }  
  26.     public Student(string name, string department)  
  27.     {  
  28.         this.Name = name;  
  29.         this.Department = department;  
  30.     }  
  31. }   
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:
  1. T obj=new T();  
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.
  1. T GetObject < T > (params object[] lstArgument)  
  2. {  
  3.     return (T) Activator.CreateInstance(typeof (T), lstArgument);  
  4. }  
So by using this method we will create the object to any class. Here I will create the object to both class like this.

  1. // Create object with default parameter.  
  2. Employee emp = GetObject < Employee > ();  
  3. emp.Name = "Sakthikumar";  
  4. emp.Address = "Chennai";  
  5. Console.WriteLine("Employee Detail");  
  6. Console.WriteLine("----------------");  
  7. Console.WriteLine("Name : " + emp.Name);  
  8. Console.WriteLine("Address : " + emp.Address);  
  9. // Create object with argumented parameter.  
  10. Student student = GetObject < Student > ("Sakthikumar""MCA");;  
  11. Console.WriteLine("Student Detail");  
  12. Console.WriteLine("----------------");  
  13. Console.WriteLine("Name : " + emp.Name);  
  14. Console.WriteLine("Department : " + emp.Address);  

Please feel free if you have any doubt regarding this.

Next Recommended Reading C# Objects and Classes