Introduction:
Generics in c# is a concept which we use for high quality better code performance boost, it is a strongly type collection, and is quite to similar to how we use Templates in C++, but since templates were only allowed to be used with classes, the Generics in C# can be applied not only to the classes but also to the Delegates, Lists, Arrays, Interfaces etc.
A generic class can be defined as,
public class myclass<T>, my class is the class name where as <T> is the generic Type 'T' which we would use in case of declaring a generic class,
We will see how the generics actually works in c# with an example, where we are going to add two numbers using the generics.
Step 1:
So lets create a new Project first in visual studio 2017, we will name it as GenericsExample,
Step 2:
So, now we will create a Generic class and we will create a few methods inside this Generic class of type T.
We named our class as myclass<T>,and for adding numbers, we will have a method accepting two parameters and returns the sum of those numbers.
We declare the local variables inside the function as dynamic, since we use dynamic type for a generalize object.
Step 3:
Now we will call the method inside this generic class from the Main function of our console application as.
We are taking the generic class as of type Int, and then passing two integers to the calling function which is AddNumbers(), then we are printing the sum in the output, here the how the entire code looks like.
Press crtl+f5 to run the application and see the output window,