Generic Class with C#

Generic class example.

  1. public class TestGeneric<T>  
  2. {  
  3.         T objectname;  
  4.   
  5.   
  6.         public simpleGeneric(T obj)  
  7.         {  
  8.             objectname = obj;  
  9.         }  
  10.   
  11.         public T getobj()  
  12.         {  
  13.             return objectname;  
  14.         }  
  15.   
  16.         public void display()  
  17.         {  
  18.             Console.WriteLine("The type is:" + typeof(T));  
  19.         }  

we have created a TestGeneric class with generic type.

  1. class Program  
  2. {  
  3.         static void Main(string[] args)  
  4.         { 
  5.             //Create object with int type
  6.             TestGeneric<int> Gen = new TestGeneric<int>(107);  
  7.             Gen.display();  
  8.             int i = Gen.getobj();  
  9.             Console.WriteLine("The Value of i:{0}", i);  
  10.              
  11.             //Create object with string type
  12.             TestGeneric<string> GenString = new TestGeneric<string>("Welcome to Generic");  
  13.             GenString.display();  
  14.             string str = GenString.getobj();  
  15.             Console.WriteLine("The Value of str:{0}", str);  
  16.             Console.ReadLine();  
  17.         }  

call with generic class with diffenet datatype.

OutPut : 
 
  1. The type is:System.Int32  
  2. The Value of i:107  
  3. The type is:System.String  
  4. The Value of str:Welcome to Generic