Hi Guys.. In this article we will learn the basics of Generics with a simple example. Its advantages and scenarios which made need for Generics.

Why we need Generics?
Consider an example program where you want to swap the integers. And you completed that.. Great.. But now requirement is to swap string.. OK you did that too.. Awesome.. Now lets assume you got a requirement to swap objects.. Are you Kidding..? How many cases will you write then?

Here evolves our concept of Generics.. The Generic one where you don’t specify the datatype before. You can later give the datatype at runtime.

The Generic class can be defined by putting the sign after the class name. And its not mandatory to use only T, you can use any word.

As described above lets create a class which will swap any two variables irrespective of their datatype

class GenericClass<T>
    {
        public void Swap(ref T A,ref T B)
        {
            T C = A;
            A = B;
            B = C;
        }
    }

Now lets create a Main class where we will initialize the above class with integers and use swap method.
Similarly we can also continue creating with other data types like in below example swapping is also done with string.


class Program
    {
        static void Main(string[] args)
        {
            int a =10;int b= 20;
            GenericClass<int> objGen = new GenericClass<int>();
            Console.WriteLine("Values before swapping are: " + a + " and " + b);
            objGen.Swap(ref a, ref b);
            Console.WriteLine("Values before swapping are: " + a + " and " + b);
            Console.ReadLine();

            string strA = "InkFort"; string strB = "Generics";
            GenericClass<string> objGenString = new GenericClass<string>();
            Console.WriteLine("Values before swapping are: " + strA + " and " + strB);
            objGenString.Swap(ref strA, ref strB);
            Console.WriteLine("Values before swapping are: " + strA + " and " + strB);
            Console.ReadLine();
        }
    }

Now lets conclude with some better feaatures of Generic types. They are not just used as common datatypes. But it has advantages

It is type safe meaning it will show compilation errors if you have used any other datatype apart from which the object is initialized.

Since it doesn’t use boxing and unboxing its performance is much faster.