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.
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
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.
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
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 < bandb < cthena < c;Compare(a, b)andCompare(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 - 1overflows and flips the sign. Usex.CompareTo(y)orint.CompareTo. - By convention
nullsorts before any non-null value.Comparer<T>.Default.Compare(null, x)follows that rule for you. - Keep
CompareToconsistent withEquals. WhenCompareToreturns zero for values thatEqualscalls different,SortedSet<T>treats them as duplicates and drops one. - Implement
IComparable<T>for the one obvious order of a type (numbers, versions, money). UseIComparer<T>for every other order, or for types you cannot change. Comparer<T>.Defaultreturns the comparer for the natural order andComparer<T>.Createbuilds one from a lambda. See Comparer.- Implementing
IComparable<T>does not give you the<and>operators. Add them yourself, or useSystem.Numerics.IComparisonOperators(see generic math). - Sorting with
Sortis not stable;OrderByis.
Related
- Comparer
- StringComparer
- List
.Sort() - SortedSet
- Lists and sorted collections in the tutorial