Topic : Generics in C# - C# Template: Generic Class | Generic Method

Generics:

Generics is an Special feature in C# just like a Template In C++ Programming language. Generics Allow us to write a Class or Method that can work with any data type. So Generic make it easier for us to use Different data types in our Program by creating a single Class or Method.



Generics: Infobrother:

Let's suppose we write an simple Program "Calculator". This Program can Add, Subtract, or can perform any Math Operation On Integers. The Program is Working fine on Any Integers. but how about, if we want to perform some operation on Float Data type. Do we need to create another Program? Obviously, we have to because our Program just works on Integers. so far any other data type, we have to write another Program. but C# provide a Tool named Generic , to make our life Easier.



  • C# Allow us to use Generic in Two Ways:

    » Class Generic:
    » Method Generic:



Class Generic:

C# allow to make a Class Generic and can use it as an Template . This Generic Class defer the Specification of Types until the Class is Instantiated. For Example - When designing a Generic class, we assume this class can work with any type. When we instantiated the class we specify the actual data type which we want to use. For defining the Generic class, we use < T > after the Class Name as follow:


public class  GenericClass<T>
{
   public void AnyMethod(T Item)
   {
      //work on T item:
   }
}


In Above Syntax We create an Generic Class to do some work. but we have not defined the actual type of item parameter. it could be any data type like int, char, float, etc. and we can use it for any type, consider the example below.


GenericClass<int>    forInteger = new GenericClass<int>();
GenericClass<float>  forfloat = new GenericClass<float>();
GenericClass<char>   forchar = new GenericClass<char>();
GenericClass<double> fordouble = new GenericClass<double>();


Let's have an example of Generic Class. In this class we will write an Generic Calculator Class. This class will take two parameters of type T and will return the sum of these two numbers. We didn't specify any data type while declaring the class. so it could be any valid data type. Look at the example below:


/*Example - Generic Class - InfoBrother*/

using System;

namespace Generic
{
    public class  Calculator<T>   //Generic Class:
    {
        private T result;  //variable of type T to show result:
        public T add(T x, T y) //Receive two Parameters of type T:
        {
            //we will discuss "Dynamic" keyword in same tutorial:
            dynamic a = x;  
            dynamic b = y;
            result = a + b;
            return result;
        }          
    }


    class Program
    {     
        static void Main(string[] args)
        {
            Calculator<int> integer = new Calculator<int>();  
            Console.WriteLine("Generic Class for Integer: " + integer.add(20, 10));

            Calculator<float> _float = new Calculator<float>();
            Console.WriteLine("Generic Class for float: " + _float.add(3.5F, 2.0F));

            Calculator<double> _double = new Calculator<double>();
            Console.WriteLine("Generic Class for Double: " + _double.add(2.22, 1.25));

            Console.ReadKey();

        }
    }
}


Dynamic Keyword:

dynamic are dynamically type variable that act like a placeholder for a type not known until runtime. Once a dynamic variable is declared we can replace it with other type valid data type as we did in our above example.



Generic Method:

C# also provides Generic Methods. We can create a Method which defer the Parameter data type until the method is called. These Parameters are Called Type parameters that means we can pass the actual data type later. Let's have an example to know how we can use generic method in C#.



/*Example - Generic Methods - InfoBrother*/

using System;

namespace Generic
{
    class Program
    {     
        //Generic Method:
        static void swap<T>(ref T x, ref T y)
        {

            T temp = x;
            x = y;
            y = temp;
        }

        static void Main(string[] args)
        {
            //Generic method for integers:
            int int1 = 15, int2 = 20;
            Console.WriteLine("Swap two Integers:\nBefore = {0} | {1}", int1, int2);
            swap<int>(ref int1, ref int2);  //swapping:
            Console.WriteLine("After = {0} | {1}", int1, int2);

            //Generic method for char:
            char ch1 = 'M', ch2 = 'O';
            Console.WriteLine("\nSwap two Character:\nBefore = {0} | {1}", ch1, ch2);
            swap<char>(ref ch1, ref ch2);  //swapping:
            Console.WriteLine("After = {0} | {1}", ch1, ch2);

            //Generic method for string:
            string str1 = "Hello" , str2 = "world";
            Console.WriteLine("\nSwap two words:\nBefore = {0} | {1}", str1, str2);
            swap<string>(ref str1, ref str2); //swapping
            Console.WriteLine("After = {0} | {1}", str1, str2);

            Console.ReadKey();

        }
    }
}


In Above Example, we have Declared a Swap() Generic method. In this method we have declared a Type Argument "T". In main method we pass swap method with different data type. and our program can handle all data type.



  • More about Generic:

    » Generic help us to maximize code reuse, type safety, and performance.
    » We can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. we may use these generic collection classes instead of the collection classes in the System.Collections namespace.
    » We can create our own generic interfaces, classes, methods, events, and delegates.
    » We can create generic classes constrained to enable access to methods on particular data types.
    » We can get information on the types used in a generic data type at run-time by means of reflection.

















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement