Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

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:

  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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# in a Nutshell

C# in a Nutshell

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

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard

Publisher Resources

ISBN: 0596005261Catalog PageErrata