So now is the the time to discuss the concept of the generic classes in C#. Before we start, let us try to figure out what exactly does this concept of generics means.
As a .net developer, you will be aware of the data type object, which is the base type of all the data types in the .net framework. We can declare a variable of type object and store any kind of value in it, whether it is a string or integer or any other type. So object data type here acts as a generic type. Similarly, we can specify classes and methods with a generic definition and any type can be specified in place of it when it is being used. In simple language, we can declare a container and use this container to perform operations, for any data type
Here, we have created a blue print of class, which can be used for any of our data type like integer, string or any custom class. We specify it to be a generic by using the <T> as type parameter. This is the most important part of the syntax, without which, it would have been a simple class. This i.e. the <T> is also known as generic type parameter.
Now we will be adding a method, which will be again using a parameter of type <T>, and then we will be using this to illustrate the functionality of generic type.
Here, we have created a method which takes an input parameter of type T, which can be any type that can be specified when we use this class, and adds it to a list which is also of type T. Finally this list is returned by the function created.
So to use this, we will be using the code as :
So here, we have used the generic class to create the integer type of listing. If you try to add any string or any other type of value, it will result in compile time error as we have declared the type of the list to be integer when we first instantiated the class as integer type. Similarly you can use this for the string type or any other type of your choice. Thus, it provides the type safety and checks the type for which it is to be used at the compile time itself.
Some of the built in generic classes that we have in C# include, Stack, LinkedList, Queue etc in the System.Collections.Generic namespace.