Generics in one of the most powerful features of C#, which was introduced in C# 2.0. Before generics, programmers used to use "object" type, to store value of any type, but it would require programmers to remember object type and it leads to various run-time errors. So, C# provides generics to remove the need for casting, improve type safety, reduce the amount of boxing required, and make it easier to create generalized classes and methods.
Generic classes and methods accept type parameters, which specify the types of objects on which they operate. In C#, you indicate that a class is a generic class by providing a type parameter in angle brackets, like this
public class Queue<T> {
//members of class here
}
Where, T
in this example acts as a placeholder for a real type at compile time. When you write code to instantiate a generic Queue, you provide the type that should be substituted for T
(Circle, Horse, int, and so on).
Let's take a look at an complete example of a Generic class in which we will be creating a class, which can be used for multiple data-types.
using System;
public class GenericClassProgram
{
public static void Main()
{
GenericClass<int> intClass = new GenericClass<int>();
//passed as int type
intClass.DoSomething(4);
GenericClass<string> stringClass = new GenericClass<string>();
//passed as string
stringClass.DoSomething("44");
}
public class GenericClass<T>
{
public void DoSomething(T item)
{
Console.WriteLine(item);
}
}
}
Output:
4
44
As you can see in the above code, we are using Generic class, in which we are creating two types of objects one as "int" and another "string".
We are using same class and same method, but with different data type.