12.3. Generic Quicksort

The code for clsQuickSort is presented in Listing 12-4. Note the second using statement in the listing that makes generics possible in the clsQuickSort class. This Generic namespace contains generic classes, structures, and interfaces to support generic dictionaries, lists, queues, and stacks. In this section we draw upon generics only as they relate to the implementation of a generic class.

The third line in Listing 12-4

public class clsQuickSort<T> where T : IComparable

— uses the generic angle bracket notation that surrounds the data type (T) that is being used by the object of the class. Recall that when you instantiated an object of a generic class, perhaps for the double data type, it took the following form:

clsQuickSort<double> dSort = new clsQuickSort<double>(dData)

Therefore, the dSort object is of type double and that becomes the T type in the opening statement of the class definition. In other words, instantiating object dSort makes the statement

public class clsQuickSort<T> where T : IComparable

appear as though the class is written as

public class clsQuickSort<double> where double : IComparable

The compiler generates the necessary code to accommodate the data types that might be passed to the generic clsQuickSort class. For the moment we'll ignore the expressions that follow the where keyword in the statement. They are discussed a little later in the chapter.

Example 12-4. Listing 12-4
using System; using System.Collections.Generic; public ...

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.