Thursday, June 25, 2009

C# Generics


Generics are the most powerful feature of C# 2.0 which allow you to define type-safe data structures, without committing to actual data types. We can use generics in classes and in structs.

To do that, use the < and > brackets, enclosing a generic type parameter.


public class MyStack
T[] myItems;
public void Push(T item)
public T Pop()

MyStack stack = new MyStack();
int number = stack.Pop();

When using a generic stack, you have to instruct the compiler which type to use instead of the generic type parameter T, both when declaring the variable and when instantiating it:

MyStack stack = new MyStack();

The advantage of this programming model is that the internal algorithms and data manipulation remain the same while the actual data type can change based on the way the client uses your server code.

Problem with object based solution

Performance isuue due to boxing/unboxing
No compile-time type safety


Significant performance boost
Higher quality code
Reuseable code and the effort
Type-safe at compile-time.
Gives no boxing, no casting advantage.