Generic Classes Using Generic Type Parameter

As a .NET developer you are aware of the data type object, that 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 the 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 instead of it when it is being used. In simple language, we can declare a container and use this container for any data type.

To start with we will be creating a class type that specifies it to be generic using the following syntax:



Here, we have created a blueprint of a class that can be used for any of our data types, 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. In other words the <T> is also known as generic type parameter.

Now we will be adding a method that will again be using a parameter of type <T> and then we will be using this to illustrate the functionality of the generic type.



Here, we have created a method that takes an input parameter of type T that can be of any type that can be specified when we use this class and adds it to a list that 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 a compile time error since 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 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 and so on in the System.Collections.Generic namespace.

Up Next
    Ebook Download
    View all
    Learn
    View all