Sunday 24 April 2016

What is Generic in c#?.



Generic allow you to define type safe classes without compromising type safety, performance or productivity.

 In other word we can say that, Generic allows you to delay the specification of the datatype programming element in class or methods or delegates, until it is actually used in the program.

Generic allows class or method or delegate that can work with any data type.

Examples:-
Generic Class :-
public class GenericClass<G>
    {
        private G[] Array;
        public GenericClass(int size)
        {
            Array =new G[size + 1];
        }

        public G GetItem(int index)
        {
            return Array[index];
        }

        public void SetItem(int index, G value)
        {
            Array[index] = value;
        }
    }
class Program
    {
static  void Main(string[] args)
        {
            // for int datatype
            GenericClass<int> intGeneric = new GenericClass<int>(10);
           
            for(int i=0;i<=10;i++)
            {
                intGeneric.SetItem(i, i * 2);
            }

            for (int j = 0; j < 10; j++)
            {
               Console.WriteLine(intGeneric.GetItem(j));
            }

            // for string datatype
            GenericClass<string> strGeneric = new GenericClass<string>(10);
            for (int i = 0; i < 10; i++)
            {
                strGeneric.SetItem(i, "test" + i);
            }

            for (int j = 0; j < 10; j++)
            {
                Console.WriteLine(strGeneric.GetItem(j));
            }
         }
}

Generic Method :-
 
class Program:Factory
    {
        static void Swap<T>(ref T t1, ref T t2)
        {
            T temp;
            temp = t1;
            t1 = t2;
            t2 = temp;
        }
static  void Main(string[] args)
        {
            int a = 2; int b = 5;
            Swap<int>(ref a, ref b);
            //a and b value after swap
            Console.WriteLine("{0}-{1}", a, b);

            char c, d;
            c = 'a';
            d = 'b';
            Swap<char>(ref c, ref d);
            //c and d value after swap
            Console.WriteLine("{0}-{1}", c, d);
                }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.