Feed the creative machine

Tuesday, February 21, 2006

C# Generics

There is a reality; most of the developers confuse about C# Generics. Actually, there is no reason for that. If your background comes from C++ or Java you may understand more easily. What "Templates" tell you from your C++ knowledge or "Generics" from Java. Main concept is same here in C# with some better extensions and easy usability. For example since C++ Templates uses compile time, C# Generics also a feature of the runtime. They are basically the capacity to have type parameters lying on your type. Generics refer to classes and methods that work homogeneously on values of different types. They are a type of data structure that contains code that remains the same; though, the data type of the parameters can change with each use. We can also call them parameterized types or parametric polymorphism.

The usage of generics within the data structure adjusts to the different data type of the passed variables. Briefly, a generic is a code template that can be applied to use the same code over and over again. Whenever the generic is used, it can be adapted for different data types without require to rewrite any of the internal code.

A List collection class can be a good example:

List Mylist1 = new List();

// No boxing or casting necessary
list1.Add (5);

If we want to expand this code and make it more sensible, we can build something like this:

using System;
using System.Collections;
using System.Text;

namespace TList
{
public class List