Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Collections

IComparer<T> and IComparable<T>

Reference for C# IComparable<T> and IComparer<T>: define a natural order for a type, plug in alternative orders, and follow the rules for a consistent CompareTo.

IComparable<T> and IComparer<T> are the two interfaces .NET uses to ask "which of these two values comes first?". A type that implements IComparable<T> has a built-in natural order: its CompareTo(T other) method compares this with another instance. A separate IComparer<T> object compares two values from outside the type, so you can offer several orders for one type or order a type you do not own.

Sorting APIs such as List<T>.Sort(), Array.Sort(), SortedSet<T>, SortedDictionary<TKey,TValue>, PriorityQueue<TElement,TPriority> and LINQ OrderBy use the natural order when you pass nothing and your comparer when you pass one.

C#
public readonly record struct Version2(int Major, int Minor) : IComparable<Version2>
{
    public int CompareTo(Version2 other) =>
        Major != other.Major ? Major.CompareTo(other.Major) : Minor.CompareTo(other.Minor);
}

Try it

C# A natural order with IComparable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Several orders with IComparer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public interface IComparable<in T>
{
    int CompareTo(T? other);
}

public interface IComparer<in T>
{
    int Compare(T? x, T? y);
}
Name Description
other The value to compare this against (IComparable<T>).
x, y The two values to compare (IComparer<T>).

Returns: a negative number if the first value sorts before the second, zero if they are equivalent, and a positive number if it sorts after. Only the sign matters: do not rely on -1, 0 and 1.

Errors: the non-generic IComparable.CompareTo(object?) throws ArgumentException when the object has the wrong type. Array.Sort() and List<T>.Sort() without a comparer throw InvalidOperationException when the element type implements no IComparable at all. An inconsistent comparer can make a sort throw InvalidOperationException ("IComparer.Compare() method returns inconsistent results") or silently produce a wrong order.

Usage notes

  • A good comparison is consistent: if a < b and b < c then a < c; Compare(a, b) and Compare(b, a) have opposite signs; Compare(a, a) is zero. Break these rules and sorting, binary search and sorted collections misbehave.
  • Never subtract to compare (x - y): int.MinValue - 1 overflows and flips the sign. Use x.CompareTo(y) or int.CompareTo.
  • By convention null sorts before any non-null value. Comparer<T>.Default.Compare(null, x) follows that rule for you.
  • Keep CompareTo consistent with Equals. When CompareTo returns zero for values that Equals calls different, SortedSet<T> treats them as duplicates and drops one.
  • Implement IComparable<T> for the one obvious order of a type (numbers, versions, money). Use IComparer<T> for every other order, or for types you cannot change.
  • Comparer<T>.Default returns the comparer for the natural order and Comparer<T>.Create builds one from a lambda. See Comparer.
  • Implementing IComparable<T> does not give you the < and > operators. Add them yourself, or use System.Numerics.IComparisonOperators (see generic math).
  • Sorting with Sort is not stable; OrderBy is.