O'Reilly logo

C# in a Nutshell by Peter Drayton, Ted Neward, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required