Introduction
This article is written to gain a clear understanding on Generics: why we use it, are there any workaround, why Generics are so important, and why we use this type-safe data structure rather than Standard Collections. This article is explained with basic examples of Generics for clear understanding.
Generics
To the people who aren't familiar with Generics in C#, Generics is simply a class that gives us access to create classes and methods with a placeholder.
So, what is a placeholder?
In programming, the meaning of placeholder is a simple character or a word or something like a string of characters that takes the position of final data temporarily.
Sounds good! Now why do we need a character to be a placeholder?
If you are aware, whenever you go through a complex program you might have seen a Character T inside Angle brackets <> just like this <T> and we ask ourselves a question, What does this <T> mean and why do we need it?
To answer this question, <T> is a simple character inside angle brackets that's telling us: "Hey coders! I’m just a generic type parameter and please put me beside a class so that I will be useful as a Type in the place of a datatype, in your program."
If you’re still wondering what the above statement meant:
It’s saying that, at present, you can use me in place of a data type, and as per your need you can replace me with my datatype friends like int, string, etc., in your program.
This example code will suffice to gain a clear understanding of Generics:
- using System;
- public class Hospital<T> //Here <T> is placed beside class Hospital
- {
- private T Cases; //Here we declared a variable named "Cases" of Type T
- public Hospital(T value) //Here in the constructor we took another variable named "value" of Type T
- {
- this.Cases=value; //Here we're referring the fields of current class Hospital using this keyword.
- }
- public void Show()
- {
- Console.WriteLine(this.Cases);
- }
- }
- // Driver Class
- class Test
- {
- static void Main(string[] args)
- {
- Hospital<int> a = new Hospital<int>(100); // Here we can see <T> is replaced with <int> that means we are using <int> in place of <T>
- Hospital <string> b = new Hospital<string("Hospital Cases"); // Here we can see <T> is replaced with <string> that means we are using <string> in place of <T>
- a.Show();
- b.Show();
- Console.ReadLine();
- }
- }

Join the conversation! Your thoughts help the community grow.