Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 182 ยท Collections

IComparable and IComparer

Learn how C# decides what "smaller" means. Implement IComparable<T>, write IComparer<T> classes and Comparison delegates, sort by several keys and avoid common bugs.

Sorting numbers or strings in C# just works, because the framework already knows how to compare them. But what does it mean to sort a list of Player objects? By name? By score? By score first and then by name? The framework cannot guess, so it asks you through two small interfaces: IComparable<T>, which gives a type a natural order, and IComparer<T>, which describes one particular order from the outside.

This lesson shows both, explains the contract that every comparison must follow, and then uses them with List<T>.Sort, Array.Sort, SortedSet<T> and LINQ. It continues the story told in sorted collections and builds on lists and abstract classes and interfaces.

The comparison contract

Both interfaces revolve around one method that returns an int:

Result Meaning
a negative number the first value comes before the second
zero the two values are equal for sorting purposes
a positive number the first value comes after the second

The exact number does not matter, only its sign. That is why int.CompareTo may return -1, 0 or 1 while string.CompareTo may return other magnitudes. Never test the result against a specific number such as == 1. Test < 0, == 0 or > 0.

flowchart LR
    A["x.CompareTo(y)"] --> B{"result"}
    B -->|"less than 0"| C["x sorts before y"]
    B -->|"0"| D["x and y are equal in order"]
    B -->|"greater than 0"| E["x sorts after y"]

Every comparison in .NET reduces to the sign of one integer.

A valid comparison must be consistent. If a comes before b, then b must come after a (antisymmetry). If a is before b and b is before c, then a is before c (transitivity). Break these rules and sorting algorithms can behave strangely, produce a wrong order or even throw InvalidOperationException.

IComparable<T>: the natural order

When a type has one obvious order, implement IComparable<T>. The interface has a single method, CompareTo(T? other), which compares this object with another one. Numbers, strings, DateTime and TimeSpan already implement it.

C# A type with a natural order

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.

Note that 1.10 sorts after 1.2: comparing the two integers is a numeric comparison, whereas comparing the text "1.10" and "1.2" would give the wrong order. The pattern in CompareTo is the one you will use most: compare the most important field, return its result if it is not zero, otherwise move on to the next field.

By convention, null sorts before everything else, which is why the method returns a positive number when other is null.

When you implement IComparable<T>, also override Equals and GetHashCode so that CompareTo(x) == 0 agrees with Equals(x). Records generate equality for you, as in the example above. If the two disagree, collections like SortedSet<T> and HashSet<T> will treat the same objects differently. See object methods.

The older non-generic interface

You will also meet the old IComparable (without <T>). Its method takes an object, so it needs casting and boxes value types. Prefer the generic one. If you implement both, forward the non-generic version to the generic one after a type check. In new code you rarely need the old interface at all, except that a few older APIs such as Array.Sort(Array) look for it.

IComparer<T>: an order from outside

A natural order is just one possibility. A player list might be shown by score on the leaderboard and by name in the roster. You cannot give the Player class two CompareTo methods, but you can write separate comparer classes, each implementing IComparer<T> with Compare(T? x, T? y).

C# Two comparers for one type

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.

The tie-break on the name matters: List<T>.Sort is not stable, so players with equal scores could otherwise come out in any order. To reverse an order, swap the two arguments (y.Score.CompareTo(x.Score)). Do not negate the result with a minus sign: -int.MinValue overflows and is still negative, which would silently break the order.

Many API methods accept an IComparer<T>: List<T>.Sort, Array.Sort, List<T>.BinarySearch, SortedSet<T>, SortedDictionary<TKey,TValue>, PriorityQueue<TElement,TPriority> and Enumerable.OrderBy. Whenever a comparer is supplied it wins over the natural order.

Comparer<T>.Create and Comparison<T>

Writing a full class for a one-off order is heavy. For List<T>.Sort and Array.Sort you can pass a Comparison<T> delegate, which is just a lambda (a, b) => int. When an API wants an IComparer<T> object instead, wrap the lambda with Comparer<T>.Create.

C# Lambdas as comparers

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.

One catch with SortedSet<T> and a comparer: two items that compare as equal are considered duplicates, and the second one is silently dropped. If your comparer only looks at length, "ddd" and "abc" would collide. Always add tie-breakers when the order is used for a set or dictionary key.

Sorting by several keys

Real data needs multi-key sorting: department, then salary descending, then name. There are three common ways.

  1. A hand-written Compare that checks one key after another, like CompareTo above.
  2. LINQ OrderBy followed by ThenBy, which reads very naturally and is stable (equal items keep their original order). See LINQ ordering.
  3. Tuple comparison: Comparer<(string, int)>.Default compares tuples item by item.
C# Multi-key sorting three ways

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.

The three lines print the same order. Negating a salary in the tuple trick is safe because real salaries are far from int.MinValue; for arbitrary integers prefer ThenByDescending.

Comparers for strings

Strings are where most sorting bugs hide. string.CompareTo and the default Sort use the current culture, so the same program can sort differently on a French and a Turkish computer. For stable, culture-independent results use StringComparer.Ordinal (compares UTF-16 code units, upper case before lower case) or StringComparer.OrdinalIgnoreCase. For text shown to users, pass StringComparer.CurrentCulture on purpose.

C# Ordinal versus ignoring case

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.

Ordinal puts every capital letter before every lower-case letter, so "Carol" comes before "alice". The case-insensitive comparer treats "Bob" and "bob" as equal, and because OrderBy is stable, they stay in their original relative order.

Common mistakes

  • Inconsistent comparers. A comparer that returns 1 for both Compare(a, b) and Compare(b, a) breaks the sorting algorithms. Test the swap case.
  • Subtracting numbers. return x.Value - y.Value; overflows for large values. Use x.Value.CompareTo(y.Value).
  • Forgetting null. Sorting collections with null items throws NullReferenceException unless the comparer handles them.
  • Comparing floating-point numbers with <. double.NaN is neither smaller nor larger than anything. double.CompareTo puts NaN first and is the safe choice.
  • Mutating a key that sits in a sorted collection. The set cannot find the item again afterwards.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a comparison method return when the first value should be placed before the second?

    Only the sign matters: negative means first before second, zero means equal, positive means first after second. Never compare the result to an exact number such as -1.
  2. 2. What is the difference between IComparable<T> and IComparer<T>?

    IComparable<T>.CompareTo defines the natural order inside the type. An IComparer<T> lives outside the type, so you can have as many different orders as you need.
  3. 3. How do you reverse the order in a Compare method?

    Writing y.Score.CompareTo(x.Score) reverses the order safely. Negating a result breaks for int.MinValue, which stays negative after negation.
  4. 4. Why can a SortedSet<T> with a length-only comparer lose items?

    A sorted set uses the comparer to define equality too. Two different words of the same length compare as 0, so only the first is stored. Add tie-breakers to the comparer.

Summary

  • CompareTo and Compare return a negative number, zero or a positive number; only the sign matters.
  • Implement IComparable<T> for a type's natural order and keep it consistent with Equals.
  • Use IComparer<T>, Comparison<T> lambdas or Comparer<T>.Create for extra orders.
  • Compare several keys in sequence, or use OrderBy/ThenBy, which is stable.
  • Choose string comparers on purpose: Ordinal for stable results, culture comparers for user-facing text.
  • Never subtract values to compare them, and always give sorted sets a full tie-breaking order.

Next lesson: classes.