Generics in C# | C#

,

Generics is a C# 2.0 extension that supports type parameters in .NET Framework. Generics permit classes, structs, interfaces, delegates, and methods to be parameterized.

Scenario for Generics in C#
Let's walk-through a code below to understand the scenario for generics.

public class Stack
{
object[] items;
int count;
public void Push(object item) {...}
public object Pop() {...}
}

The above code shows a stack class that simply handles a collection object via stack mechanism. Any type of data can be stored in object type. The stack class stores an item via Push method and removes/retrieves an item via Pop method. when an int type value is passed to the Push method, it is automatically boxed. It must be unboxed with an explicit type cast while retrieving the value

Stack stack = new Stack();
stack.Push(3);
int i = (int)stack.Pop(); 

We can clearly see that it involves dynamic memory allocations and run-time type checks. We cannot enforce the kind of data placed on a stack. So accidental wrong casting in runtime may lead to an exception.

Stack stack = new Stack();
stack.Push("string value");
int s = (int)stack.Pop();

The above code will not through a compile-time error. However, an InvalidCastException is thrown at runtime. We can avoid such scenario by using Generics. Using Generic type parameter you can avoid unnecessary boxing and unboxing.

What is Type Parameters in C# Generics?
A Placeholder for a type that can be decided or specified when instantiating a generic type.

Implementing Generics in C#

We can avoid the above scenario using Generics. Lets rewrite the class Stack by introducing generic class as below

public class Stack
{
T[] items;
int count;
public void Push(T item) {...}
public T Pop() {...}
} 

The Generic class Stack is instantiated by substituting the type T (placeholder for types) with the actual type. The below code shows the usage of int for Generic Type Parameter

Stack stack = new Stack();
stack.Push(3);
int x = stack.Pop(); 

Every occurrence of T is replaced with the type argument int when Stack is instantiated as new Stack()