12.2. What are Generics?

Simply stated, generics enable you to create "typeless" data structures in C#. In the Quicksort example presented earlier, you defined an instance of the clsSort object with the following syntax:

clsSort mySort = new clsSort(data);

As you saw, the problem is that the algorithm is based upon using an int data type for the processing. With a generic class, the definition becomes:

clsSort<T> mySort = new clsSort<T>(data);

The data type you wish to use is substituted for the term T within the enclosing angle brackets. For example, if you wish to sort the int data values stored in the data array, you would use this code:

clsSort<int> mySort = new clsSort<int>(data);

In some later project that uses the double data type, you would use this code:

clsSort<double> mySort = new clsSort<double>(data);

One of the key advantages of generics is that the same code can process different data types without the source code being changed for each data type! If you write a class using the generic model, that class can process different data types without your having to craft methods for each data type. The Visual Studio compiler generates the necessary code to handle the different data types for you.

12.2.1. Generics Versus ArrayLists

You might be saying, "Wait a minute! Can't ArrayLists do the same thing?" Well, not really. ArrayLists suffer from a few messy limitations. Consider the following code fragment:

ArrayList a = new ArrayList(); int i = 5; a[0] = i; a[1] = "t"; ...

Get Beginning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.