Generics in C#


public class Stack<T> : IEnumerable<T>, ICollection, IEnumerable
{
}

Any body seen a class something similar to this, and surprised about what would be <T> means ? Stack class can be called as Generic type. They are newly introduced in .NET2005. It’s something similar to C++ templates. But it is not exactly like templates. It lacks some functionalities that templates have.

What does a Generic class or method means ?

When programs are becoming more complex, we need some method to avoid errors and provide maximum perfection. Class user can define which type has to be passed to class in Generic classes. See the below example which explains a Generic class that keeps objects in ArrayList.


class Program
{
static void Main(string[] args)
{

MyGenericClass<int> m1 = new MyGenericClass<int>();
}
}

class MyGenericClass<T>
{
private ArrayList ObjArr = new ArrayList();

public void AddObject(T t)
{
ObjArr.Add(t);
}
}

In the above example, <T> is a generic type, and it’s type will be defined at the time of class object creation.

MyGenericClass<int> m1 = new MyGenericClass<int>();

This line assigns <T> to integer type.

Generics can be applied for classes, methods , properties etc..

Where do we use it ?

Assume you are writing a program and implementing “undo” functionality. Normally undo operation use a Stack class. All the user activity will be stored in Stack, and it will be restored when undo command issues.

Normally Stack class collects all the variables of type object. It won’t validate whether the object is correct type that needs for undo operation. By writing a generic class this can be avoided. So it can hold only the specified type of objects.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s