Generic Method and Generic Class in C#
Generics allow the reuse of code across different types. It helps to reduce writing redundant code.
This mechanism is also known as “Templates” in C++
Generic Method
For example, let’s declare a ‘Swap method’ to swap the values of its two parameters:
The ‘Swap method’ will work only for ‘integer’ parameters. If we want to use it for other types such as double or string, we have to overload the method then change the type of its parameters to double or string every time.
Due to a lot of code repetition, it becomes harder to manage the code. Generics provide a flexible mechanism to fix this issue.
Example of definition a generic type:
In the code above, T is the name of the generic type. We can name it anything we want, but T is a commonly used name.
The Swap method now takes two parameters of type T, and we also use the T type for ‘temp’ variable.
Note the brackets <T> in the syntax, which are used to define a generic type.
Now we can use the Swap method with different types:
Output:
When calling a generic method, we need to specify the type by using brackets <>.
Swap<int>…The T type is replaced by int.
Swap<string>…The T type is replaced by string.
If you omit specifying the type when calling a generic method, the compiler will use the type based on the arguments passed to the method.
Multiple generic parameters can be used with a single method. For example:
Func<T, U> takes two different generic types.
Output:
Func<T, U, V> takes three different generic types.
Output:
Generic Class
Generic types can also be used with classes. The most common use for generic classes is with collections of items, such as adding or removing items from the collection regardless of the type of data being stored.
One type of collection is called a ‘stack’. Items are pushed or added to the collection, and popped or removed from the collection.
A stack is sometimes called a Last In First Out (LIFO) data structure.
For example:
The generic class stores elements in an array, and the generic type T is used as:
- the type of the ‘innerArray array’
- the parameter type of the ‘Push method’
- the return type of the ‘Pop method’
Now we can create objects of the Stack generic class:
Stack<int>
Output:
Stack<double>
Output:
In a generic class we don’t need to define the generic type for its methods because the generic type is already defined on the class level.