Generics in C#

Today we are going to understand the concept of Generics in C#. When it is introduced, why it is introduced, what are its benefits and how and where it can be used.

Brief Description:

Dictionary meaning of Generics is General. So in Generics we are generalizing the types either they are class, methods, interfaces etc. While creating class or other types we are not restricting its data type, it is defined at the time of instantiating according to the requirement.

Let us understand the above defination with examples:
Generics
What is the problem in the above code. Can you guess??
Let me help you out for now we have 2 data types to compare with. So we declared two overloaded methods doing same thing i.e., Comparison. Suppose in future we need to compare more data types!!!!!!




Problems with above code:

  • Code Repetition – Suppose in future we need to compare other data types also like float / decimal / object type etc. Then we have to create overloaded methods for each data type, which is very impractical way or also a very tedious job.
  • Repetition of the same code many times cause your application error prone.
  • Bug fixing – While fixing any bug in the defined data structure you have to fix it not only in one place but in all the places where you use the type specific duplicates.

So here comes ‘Generics’ introduced in C# 2.0. Here we don’t have to define the data type of input parameters. Then question is how we can create a method without writing data type of its input parameters?????
The answer is by making the class Generic.

public bool Compare(T value1, T value2) {........}

Here letter ‘T’ is the unknown data type, defined at the time of creating the instance of the class. Let me show you how.

public class GenericExample<T>
{
public bool Compare(T value1, T value2) {// code goes here}
}
public class Program
{
static void Main(string[] args)
{GenericExample<T> obj = new GenericExample<T>();} // You can give any data type here
}

Full Code
Generics