Ordering Instances
The implementations of
the collection classes’
sorting and searching capabilities depend on certain facilities in
the contained objects themselves. The most common of these are the
ability to order the contained objects (used for sorting and
efficient searching) and the ability to hash an object (to speed
storage and retrieval in dictionary-based structures such as
Hashtable). As with most other parts of the
FCL’s collections framework, this is accomplished
via standardized interfaces and overridden virtual methods on
System.Object.
The IComparable Interface
The IComparable interface
allows one object to indicate its
ordering relative to another instance of the same type. To allow
sorting and searching of your types in an array, implement the
IComparable interface, which looks like this:
public interface IComparable {
int CompareTo(object rhs);
}Implementation of this interface should follow the following semantic rules:
If
acomes beforeb→a.CompareTo(b) < 0If
ais equalb→a.CompareTo(b) = = 0If
acomes afterb→a.CompareTo(b) > 0nullcomes first:a.CompareTo(null) > 0a.CompareTo(b)→a.GetType( ) = = b.GetType( )
An example implementation of this interface might look like this:
public sealed class Person : IComparable { public string Name; public int Age; public int CompareTo(object o) { // Check for null if (o= =null) return 1; // Check for concrete type match if (o.GetType( ) != this.GetType( )) throw new ArgumentException( ); // Sort instances by ...