Generics fundamentals in C#.NET

 Generics

Generics is a new concept in .net 2.0 and this is similar to templates in C++. By using generics, you can create generic methods and generic classes.

Generic Methods
A generic method is a method that can operate on any type of data. For most of the algorithms, logic is same whatever the type of data is. Hence instead of creating one method for every data type, you can create only one method that can accept any type of arguments, which is called as generic method. To create a method as generic method, syntax is as follows.
            [Access Modifier] returntype MethodName<GenericTypes>([Parameters])
            {
           
            }
After creating a generic method, to call the generic method syntax is as follows.
                                    MethodName<DataType>([Arguments])

Example : 
The following example creates a method Swap() as a generic method that can swap two values that can be of any type.

namespace Generics
{
    class Program
    {
        public static void Swap<MyType>(ref MyType X, ref MyType Y)
        {
            MyType T;
            T = X;
            X = Y;
            Y = T;
        }
        static void Main(string[] args)
        {
            int A = 10, B = 20;
            float F1 = 3.5F, F2 = 5.5F;
            string S1 = "Naresh", S2 = "Microsoft";
            Swap<int>(ref A, ref B);
            Swap<float>(ref F1, ref F2);
            Swap<string>(ref S1, ref S2);
            Console.WriteLine("After Swap ...");
            Console.WriteLine("A = {0}\tB = {1}", A, B);
            Console.WriteLine("F1 = {0}\tF2 = {1}", F1, F2);
            Console.WriteLine("S1 = {0}\tS2 = {1}", S1, S2);
        }
    }
}

Constraints On Generic Types
A generic type by default can accept any type of data. But there are some situations where you have to restrict your generic type to accept only certain types and for this you have to specify constraints on generic types. To specify constraints on generic types, you have to use the keyword where at the end of the method declaration as follows

[Access Modifier] returntype MethodName<GT>([Parameters]) where GT : constraints
{
           
}
You can specify the following constraints on generics.
  1. Struct : this makes the generic type accept only value types.
  2. Class : this makes the generic type accept only reference types.
  3. <classname> : this makes the generic type accept only that particular class and its derived classes.
  4. <interfacename> : this makes the generic type accept only the types that implement that interface.
  5. You can specify multiple constraints on generic types by separating them with comma(,). But combination of constraints like struct and class are not allowed as there is no type in .net that is both value type and reference type.

Example : 
The following example creates a method Sort() as generic method that can sort any type of array.

namespace Generics
{
    class GenSort
    {
        public static void Sort<MyType>(params MyType[] A) where MyType : IComparable
        {
            MyType T;
            for (int i = 0; i < A.GetLength(0); i++)
            {
                for (int j = i + 1; j < A.GetLength(0); j++)
                {
                    if (A[i].CompareTo(A[j]) > 0)
                    {
                        T = A[i];
                        A[i] = A[j];
                        A[j] = T;
                    }
                }
            }
        }
        static void Main()
        {
            int[] A = { 23, 9, 17, 12, 3 };
            float[] F = { 27.32F, 56.66F, 32.21F, 17.76F, 21.21F };
            string[] S = { "Microsoft""Sun""Oracle""Adobe""Ibm" };
            Sort<int>(A);
            Sort<float>(F);
            Sort<string>(S);
            Console.WriteLine("After Sort Values In Arrays Are...");
            foreach (int n in A)
            {
                Console.Write("{0}\t", n);
            }
            Console.WriteLine();
            foreach (float n in F)
            {
                Console.Write("{0}\t", n);
            }
            Console.WriteLine();
            foreach (string n in S)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Multiple Generic Types
There may be a situation where you have to take more than one parameter for a generic method that are of different type. In this case generic method can be created with more than one generic type. Syntax is as follows.
[Access Modifier] returntype MethodName<GT1,GT2,…>([Parameters])
            {
           
            }
After creating a generic method with multiple generic types, to call the generic method syntax is as follows.

                        MethodName<DataType1,DataType2,…>([Arguments])

Example : 
The following example creates a method with the name Print() as a generic method that accepts two parameters of two different types.

namespace Generics
{
    class MultiGen
    {
        public static void Print<MyType1, MyType2>(MyType1 X, MyType2 Y)
        {
            Console.WriteLine("X = {0}\tY = {1}", X, Y);
        }
        static void Main()
        {
            Print<intfloat>(10, 14.5F);
            Print<floatstring>(23.34F, "Naresh");
            Print<stringstring>("Microsoft""Naresh");
        }
    }
}

Generic Methods With Parameters of Standard types
When the method is declared as generic method then it is not compulsory that every parameter of that method must be of generic type. A generic method can have the parameters of standard type and for these parameters you must pass only that particular type of arguments.

Example : 
the following example creates a method with the name “Print” as a generic method that takes one generic type parameter and one int parameter.

namespace Generics
{
    class StandardTypes
    {
        static void Print<MyType>(MyType X, int N)
        {
            for (int i = 0; i < N; i++)
            {
                Console.Write("{0}\t", X);
            }
            Console.WriteLine();
        }
        static void Main()
        {
            Print<int>(3, 5);
            Print<string>("*", 5);
            Print<double>(5.7, 3);
        }
    }
}

Generic Classes
Not only methods, classes can also be created as generic classes. A generic class is a class whose instances each can work on a different type of data. For creating a class as generic class syntax is as follows.
                        [Access Modifier] class classname<generictypes>
                        {
                        }
After creating generic class, to create an instance for the generic class, syntax is as follows.
            Classname<Datatypes> ObjName = new classname<datatypes>();

Example : 
The following example creates a class with the name Test as generic class

namespace Generics
{
    class Test<MyType>
    {
        MyType A, B;
        public Test(MyType X, MyType Y)
        {
            A = X;
            B = Y;
        }
        public void Print()
        {
            Console.WriteLine("A = {0}\tB = {1}", A, B);
        }
    }
    class GenricClass
    {
        static void Main()
        {
            Test<int> T1 = new Test<int>(10, 20);
            Test<float> T2 = new Test<float>(3.5F, 4.5F);
            Test<string> T3 = new Test<string>("C#.Net""VB.Net");
            T1.Print();
            T2.Print();
            T3.Print();
        }
    }
}

You can specify constraints on generic types in generic classes also and for this purpose syntax is as follows.
                        [Access Modifier] class classname<GT> where GT : constraints
                        {

                        }
A generic class can also be created with more than one generic type same as a generic method and has the following syntax.
                        [Access Modifier] class classname<GT1,GT2,…>
                        {

                        }
When a generic class is created with more than one generic type then an instance is created for that class as follows.
Classname<DT1,DT2,…> Objname = new classname<DT1,DT2,…>();


Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.

No comments:

Post a Comment