Thursday, June 25, 2009

C# Generics

Introduction

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.

E.g.,

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

MyStack stack = new MyStack();
stack.Push(1);
stack.Push(2);
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

Advantages

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

0 comments: