What is Generic Class?

DWQA QuestionsCategory: C SharpWhat is Generic Class?
Editor Staff asked 9 months ago

What is Generic Class?

1 Answers
Editor Staff answered 9 months ago

Generic classes are defined using a type parameter in an angle brackets after the class name. The following defines a generic class.

Example: Define Generic Class
class DataStore
public T Data { get; set; }
Above, the DataStore is a generic class. T is called type parameter, which can be used as a type of fields, properties, method parameters, return types, and delegates in the DataStore class. For example, Data is generic property because we have used a type parameter T as its type instead of the specific data type.

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. Learn more about Type Parameter Naming Guidelines
You can also define multiple type parameters separated by a comma.

Example: Generic Class with Multiple Type Parameters
class KeyValuePair
public TKey Key { get; set; }
public TValue Value { get; set; }
Instantiating Generic Class
You can create an instance of generic classes by specifying an actual type in angle brackets. The following creates an instance of the generic class DataStore.

DataStore store = new DataStore();
Above, we specified the string type in the angle brackets while creating an instance. So, T will be replaced with a string type wherever T is used in the entire class at compile-time. Therefore, the type of Data property would be a string.

The following figure illustrates how generics works.

C# Generics
You can assign a string value to the Data property. Trying to assign values other than string will result in a compile-time error.

DataStore store = new DataStore();
store.Data = “Hello World!”;
//obj.Data = 123; //compile-time error
You can specify the different data types for different objects, as shown below.

Example: Generic class
DataStore strStore = new DataStore();
strStore.Data = “Hello World!”;
//strStore.Data = 123; // compile-time error

DataStore intStore = new DataStore();
intStore.Data = 100;
//intStore.Data = “Hello World!”; // compile-time error

KeyValuePair kvp1 = new KeyValuePair();
kvp1.Key = 100;
kvp1.Value = “Hundred”;

KeyValuePair kvp2 = new KeyValuePair();
kvp2.Key = “IT”;
kvp2.Value = “Information Technology”;