In C#, the term “generic” refers to a type that is not limited to a specific data type.

They allow you to define classes, interfaces, and methods with placeholders for data types. This enables you to create reusable, type-safe code that can work with any data type.

Generic type is declared by including a type parameter, represented by <T>.

public class MyClass<T>
{
private T data;
public MyClass(T field) {
data = field;
}
public T MyMethod() {
return data;
}
}

You can then instantiate MyClass with different data types:

MyClass<int> intInstance = new MyClass<int>(5);
MyClass<string> stringInstance = new MyClass<string>("Hello");

Note : It is not required to use T as a type parameter. You can give any name to a type parameter. Generally, T is used when there is only one type parameter. It is recommended to use a more readable type parameter name as per requirement like TSession, TKey, TValue etc.

Multiple Type Parameters

You can also define multiple type parameters separated by a comma.

public class Person<TValue, TKey>
{
public TValue Name { get; set; }
public TKey Age { get; set; }
}
Person<string,int> person = new Person<string, int>();
person.Name = "John David";
person.Age = 25;

Advantages of Generics:

ㅡ Generics increase the reusability of the code. You don't need to write code to handle different data types.

ㅡ Generics are type-safe. You get compile-time errors if you try to use a different data type than the one specified in the definition.

ㅡ Generic has a performance advantage because it removes the possibilities of boxing and unboxing.