What are Generics?
It’s kind of difficult to explain what ‘Generics’ are but if you have used a list before in your coding, you unknowingly know ‘Generics’.
Prerequisites
You should at least know ‘List’ Data Structures in C# and how to use them.
Usually, developers create a C# list in the following manner.

The red square box indicates generics. It restricts the addition of only ‘Integer’ items in the list.
Why Generics?
Before ‘Generics’ was introduced in C#, List was used in the following manner.
- ArrayList arrayList = new ArrayList();
- arrayList.Add(0);
- arrayList.Add(10);
- arrayList.Add("Sam");
- arrayList.Add(30);
- arrayList.Add("Jacob");
The problem with the above code is that you can add any ‘Type’ in list (Observe how ‘string’ and ‘integer’ are added to the list.)
If you do so, it will be a problem at the time of retrieval because if you try to fetch items at the index, it will return ‘object’ and you can’t do much with it.
The solution is to ‘Cast’ the retrieved ‘object’ to the required type as follows.
- var v = (int)arrayList[1];
But in real life, lists are made up of thousands of elements. It’s inconvenient to verify each element and then cast it. In case casting is not possible, the program will throw an exception. Please see the following image.

You can see we are trying to cast ‘string’ to ‘int’ which is not possible, hence the code throws an exception.
To overcome this problem, ‘Generics’ were introduced.
When to use Generics?
Anytime you create a list, you are utilizing ‘Generics’; not creating them or using them.
- private List<int> intList = new List<int>();
So, the question comes when to use ‘Generics’ and when to not.
Any time in your code you want the logic to be applicable to ‘All Types’, you can use ‘Generics’.
Explanation
Let’s assume that developers of the ‘List’ Data Structure for ‘Integers’ wrote the following code.
- class MyListInteger
- {
- private List<int> intList = new List<int>();
- public void Add(int number)
- {
- intList.Add(number);
- }
- public int GetItem(int index)
- {
- return intList[index];
- }
- }
Rajanikant HawaldarPosted Jul 4, 2019, 1:05 PM
how generic methods works if I pass index as -1?
Ravi PatelPosted Jun 29, 2019, 2:41 AM
Nice explanation
Anurag MaheshwariPosted Jun 27, 2019, 1:04 AM
Very nice and clean explanation!
Amit MohantyPosted Jun 26, 2019, 2:08 AM
Nice article !!!