Creating and using a generic class or method
Generics is a very interesting way of writing code. Instead of specifying the data type of the elements in the code at design time, you can actually delay the specification of those elements until they are used in code. This basically means that your class or method can work with any data type.
Getting ready
We will start off by writing a generic class that can take any data type as a parameter in its constructor and do something with it.
How to do it…
- Declaring a generic class is actually very easy. All that we need to do is create the class with the generic type parameter
<T>
:public class PerformAction<T> { }
Note
The generic type parameter is basically a placeholder for a specific type that will need to be defined when the class of variable is instantiated. This means that the generic class
PerformAction<T>
can never just be used without specifying the type argument inside angle brackets when instantiating the class. - Next...