Generics 101
Another new feature of C# 2.0 is the ability to create classes that can handle different types while eradicating type boxing on the underlying type. This new feature is called Generic Classes.
This type of class enable its user to create a somewhat “general class” that could accommodate any types. By using this class there is no need for type casting thus reducing the possibility of runtime errors.
Generic classes are most widely used on user-defined collections. In the previous version (framework 1.1) you are forced to implement collections using object as its underlying type so that it could store any types. This implementation would result into runtime type checking and type casting. To avoid this you can implement a class for each type that you are planning to support, thus creating an overhead of multiple implementations of a class.
Here’s a scenario. You are creating a user defined collection which has the capability to convert its stored values into a csv file. The first step is to inherit from a collectionbase class. Second is to implement your add/remove/get methods. Here then comes the problem, what type would my get function return? Or what type would my add function receive?
Generic class is the solution for the problem above.
Here’s the proper syntax for declaring a Generic Class:
public class GenericClass<T> {
T _value;
public GenericClass(){}
public void setValue(T data) {
_value = data;
}
public T getValue() {
return _value;
}
}
Let’s examine this class. The first odd thing that you would notice is the angle bars located right after the class name. These angle bars encapsulates the type that this class uses. After specifying the type, you can then use it like a normal type. By default the <T> would act as an object type within your class.
To use the above class in your program, you can initialize it this way:
GenericClass<int> generic = new GenericClass<int>();
Try to check if your setValue and getValue functions return an int which was the specified type within the angle bars.

As you can see, both of the methods of the class now returns int.
In C# 2.0 there are already Collection based Generics that’s readily available. Most likely, you’ll going to use these classes rather than create one yourself.
• List is the generic class corresponding to ArrayList.
• Dictionary is the generic class corresponding to Hashtable.
• Collection is the generic class corresponding to CollectionBase.