
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
108
|
Chapter 3: Classes and Structures
Discussion
By implementing the IComparable interface on your class (or structure), you can take
advantage of the sorting routines of the
Array, ArrayList, List<T>, and SortedList
classes. The algorithms for sorting are built into these classes; all you have to do is
tell them how to sort your classes via the code you implement in the IComparable.
CompareTo
method.
When an array of
Square objects is passed to the Array.Sort static method, the array
is sorted using the
IComparable interface of the Square objects. The same goes for the
ArrayList.Sort method. The Add method of the SortedList class uses this interface to
sort the objects as they are being added to the
SortedList.
The Array.Sort and ArrayList.Sort methods use the QuickSort algo-
rithm to sort an array’s elements.
IComparer is designed to solve the problem of allowing objects to be sorted based on
different criteria in different contexts. This interface also allows you to sort types that
you did not write. If you also wanted to sort the
Square objects by height, you could
create a new class called
CompareHeight, shown in Example 3-6, which would also
implement the
IComparer interface.
public override string ToString( )
{
return ("Height:" + height + " Width:" + width);
}
}
Example 3-6. Making a type ...