Friday 28 March 2014

Generic Class in C#

Generic Class is a class whose instances can work on different types of data. Not only methods classes also can be created as generic classes.

Syntax of Generic Class

[AccessModifier] Class classname<generictype>
{

}

Syntax for Creating Generic Class instance

classname< datatype> objectname = new classname< datatype>(); 

Example for Generic Class in .NET

using System;

namespace Generics
{
    //Generic Class
    class GenericClass<MyType>
    {
        //Private Fields
        private MyType A, B;


        //Parameterized Constructor
        public GenericClass(MyType x, MyType y)
        {
            A = x;
            B = y;
        }


        public void Print()
        {
            Console.WriteLine("A={0},  B={1}", A, B);
        }

    }


    //Main Class
    class ProgramCall
    {


        static void Main()
        {
            //Instantiating the genric class with int type
            GenericClass<int> intobject = new GenericClass<int>(10, 20);
            intobject.Print();

            //Instantiating the genric class with string type
            GenericClass<string> stringobject = new GenericClass<string>("Generic Method""Generic Class");
            stringobject.Print();

            Console.Read();

        }

    }

}


Output
A=10, B=20
A=Generic Method, B=Generic Class

No comments:

Post a Comment