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.
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 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) == 0should meana.Equals(b), otherwiseSortedSet<T>(which uses order) andHashSet<T>(which uses equality) disagree about duplicates. nullsorts first. By convention any instance is greater thannull, so aCompareToon a class handlesother is nullby returning a positive value.- Use the built-ins.
int.CompareTo,string.CompareOrdinal,DateTime.CompareandComparer<T>.Defaultdo most of the work. For several fields, compare in priority order, or use tuples:(Major, Minor).CompareTo((o.Major, o.Minor)). - Avoid
a - bfor ints. It can overflow and give the wrong sign. UseCompareTo. - 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.OrdinalorOrdinalIgnoreCasefor identifiers. This runner uses invariant globalization. - Failing sort: a type that implements neither interface makes
Sort()throwInvalidOperationException, 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 abstractIComparisonOperators<,,>from generic math.