Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Classes and Object-Oriented Concepts

IComparable and IEquatable

Reference for IComparable<T> and IEquatable<T> in C#: giving types a natural order and typed equality, CompareTo rules, operators and sorting examples.

IEquatable<T> and IComparable<T> are the two small generic interfaces that let your type take part in the framework's generic algorithms. IEquatable<T> has one method, bool Equals(T? other), used by List<T>.Contains, HashSet<T> and Dictionary<TKey,TValue>. IComparable<T> has one method, int CompareTo(T? other), used by Array.Sort, List<T>.Sort, SortedSet<T>, Enumerable.Max and Comparer<T>.Default.

Implement them on types that have an obvious natural identity and order: versions, money, coordinates on a line, priorities. For other orderings pass an IComparer<T> or a Comparison<T> at the call site instead.

C#
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

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# Classes, null and the non-generic trap

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 IEquatable<T>
{
    bool Equals(T? other);
}

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

public interface IComparable            // older, non-generic
{
    int CompareTo(object? obj);
}
Member Description
Equals(T? other) true if the two values are equal. Must agree with Equals(object) and GetHashCode().
CompareTo(T? other) Returns a negative number if this instance sorts before other, zero if the same position, a positive number if after.

The exact value returned is not part of the contract; only the sign matters, so do not compare the result to -1 or 1.

Usage notes

  • Make the two consistent. a.CompareTo(b) == 0 should mean a.Equals(b), otherwise SortedSet<T> (which uses order) and HashSet<T> (which uses equality) disagree about duplicates.
  • null sorts first. By convention any instance is greater than null, so a CompareTo on a class handles other is null by returning a positive value.
  • Use the built-ins. int.CompareTo, string.CompareOrdinal, DateTime.Compare and Comparer<T>.Default do most of the work. For several fields, compare in priority order, or use tuples: (Major, Minor).CompareTo((o.Major, o.Minor)).
  • Avoid a - b for ints. It can overflow and give the wrong sign. Use CompareTo.
  • Struct implementations avoid boxing when called through the generic interface, so implement the generic one, not only the old IComparable.
  • Strings: culture-based comparison is slower and culture dependent. Use StringComparison.Ordinal or OrdinalIgnoreCase for identifiers. This runner uses invariant globalization.
  • Failing sort: a type that implements neither interface makes Sort() throw InvalidOperationException, wrapping the real cause (see the second example).
  • Operators are optional. <, > and == are conveniences you add yourself; the interfaces do not create them. Generic code can use the static abstract IComparisonOperators<,,> from generic math.