Generic in C#
In c#, generic is a type which is used to define a class,structure,interface or method with a placeholders (type parameters) to indicate that they can store or use one or more of the types. C#, the compiler will replace a placeholders with the specified type at compile time.
C#, mostly we will use a generics with collections and the methods that operate on them to specify a type of objects to be stored in a collections. The generics are introduced in .NET Framework 2.0 with a new namespace called System.Collections.Generic.
In c#, generics are useful to improve the code re-usability, type safety and the performance when compared with the non-generic types such as arraylist.
C# Generics Declaration
To define a class or method as generic, then we need to use a type parameter as a placeholder with an angle (<>) brackets.
public class GenericClass<T>
{
public T message;
public void genericMethod(T studentname, T Address)
{
Console.WriteLine("{0}", message);
Console.WriteLine("Name: {0}", studentname);
Console.WriteLine("Location: {0}", Address);
}
}
If you see above class, we created a class (GenericClass) with one parameter (message) and method (genericMethod) using type parameter (T) as placeholder with an angle (<>) brackets.
Here, the angle (<>) brackets will indicate a GenericClass is generic and type parameter (T) is used to accept a requested type. The type parameter name can be anything like X or U or etc. based on our requirements.
Generally, while creating an instance of class we need to specify an actual type, then the compiler will replace all the type parameters such as T or U or X, etc. with specified actual type. In c#, following is the example of creating an instance of generic class.
GenericClass<string> generic= new GenericClass<string>();
generic.message = "Generic in C#";
generic.genericMethod("Code Hunger", "India");