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 it’s 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:

  1. If a comes before b a.CompareTo(b) < 0

  2. If a is equal b a.CompareTo(b) == 0

  3. If a comes after b a.CompareTo(b) > 0

  4. null comes first: a.CompareTo(null) > 0

  5. a.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 ascending ...

Get C# in a Nutshell 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.