Friday, 2 March 2012

How to Create an Generic Class?


Yes , we have many  Generic classes in .NET like List<T> .not only just utilizing them we can also create our own Generic Classes like below
  class type<mytype>
    {
            mytype A,B;
            public type(mytype x, mytype y)// parameterized constructor           
            {                                  
                A = x;
                B = y;           
            }
            public void print()
            {
                Console.WriteLine("A:{0}\tB:{1}", A, B);
            }
    }      
Here type is generic class which operates on any type of data.
this data can be int,float,double,employee,student….ect.
class GenericDemo     
    {
        static void Main()
        {
// each object t1,t2,t3 objects of type class works on different  types data.
    type<int> t1 = new type<int>(10, 20);
    type<double> t2=new type<double>(12.5,5.6);
    type<string> t3 = new type<string>("kasi","viswanadh");                       
    t1.print();
    t2.print();
    t3.print();
    Console.Read();
        }
}

No comments:

Post a Comment