O'Reilly logo

Pro C# 2010 and the .NET 4 Platform, Fifth Edition by Andrew Troelsen

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

9.13. Building Comparable Objects (IComparable)

The System.IComparable interface specifies a behavior that allows an object to be sorted based on some specified key. Here is the formal definition:

// This interface allows an object to specify its
// relationship between other like objects.
public interface IComparable
{
  int CompareTo(object o);
}

NOTE

The generic version of this interface (IComparable<T>) provides a more type-safe manner to handle comparisons between objects. You'll examine generics in Chapter 10.

Let's assume you have a new Console Application named ComparableCar that defines the following updated Car class (notice that we have basically just added a new property to represent a unique ID for each car and a modified constructor): ...

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