IComparable - how objects are compared in C#
Three different questions about "comparing" objects
Before we get to IComparable, it is worth separating three different questions that are easy to confuse, because we call them all "comparing":
- "Are these two objects the same?" - that is
Equals()/GetHashCode(), which we covered withrecordvsclass - "Which object is smaller/larger?" - that is
IComparable<T>/CompareTo()- the topic of this page - "Is this object identical in memory?" - that is
ReferenceEquals()
IComparable answers only the second question - it defines the natural sort order for a type.
The IComparable<T> interface - the definition
public interface IComparable<T>
{
int CompareTo(T other);
}
The contract of the returned value - this is the most important thing to remember:
Result of CompareTo() |
Meaning |
|---|---|
| A negative value (e.g. -1) | The current object is "smaller" than other |
| Zero | The objects are "equal" in terms of sort order |
| A positive value (e.g. 1) | The current object is "greater" than other |
An important conceptual trap: CompareTo() == 0 doesn't have to mean the objects are "equal" in the Equals() sense - these are two independent contracts. It can happen that you sort orders by date and two different orders have an identical date (CompareTo() == 0), but they are completely different objects (Equals() returns false).
Implementation - a concrete example
public class Order : IComparable<Order>
{
public int Id { get; set; }
public decimal TotalAmount { get; set; }
public int CompareTo(Order other)
{
if (other == null) return 1; // every object is "greater" than null
return TotalAmount.CompareTo(other.TotalAmount); // deleguj do CompareTo typu decimal
}
}
var order1 = new Order { Id = 1, TotalAmount = 100 };
var order2 = new Order { Id = 2, TotalAmount = 250 };
int result = order1.CompareTo(order2); // -1 (or another negative value) - order1 is "smaller"
Note that the implementation delegates the comparison to TotalAmount.CompareTo(other.TotalAmount) - decimal (like int, string, DateTime) already implements IComparable<T> internally, so you don't have to write the comparison logic "by hand" (checking <, > separately).
Why this is useful - Array.Sort() / List<T>.Sort()
var orders = new List<Order>
{
new Order { Id = 1, TotalAmount = 300 },
new Order { Id = 2, TotalAmount = 100 },
new Order { Id = 3, TotalAmount = 200 }
};
orders.Sort(); // works ONLY because Order implements IComparable<Order>!
// result: [100, 200, 300] - sorted by TotalAmount, because that is how we defined CompareTo
Without an implementation of IComparable<Order>, calling orders.Sort() wouldn't compile (or, for the older non-generic IComparable, would throw an exception at runtime) - List<T>.Sort() with no parameters requires the element type to know by itself how to compare itself.
SortedSet<Order> sortedOrders = new(); // ALSO requires IComparable<Order> (or an IComparer<Order>)
sortedOrders.Add(order1);
sortedOrders.Add(order2); // automatically inserted in the RIGHT place, according to CompareTo
IComparer<T> - when you need MANY different ways of comparing
IComparable<T> gives only one "natural" order (here: by TotalAmount). What if you sometimes want to sort by customer name and sometimes by date? That is what the separate IComparer<T> interface is for - an external comparer, independent of the class itself:
public class OrderByCustomerNameComparer : IComparer<Order>
{
public int Compare(Order x, Order y) => string.Compare(x.CustomerName, y.CustomerName);
}
public class OrderByDateComparer : IComparer<Order>
{
public int Compare(Order x, Order y) => x.CreatedDate.CompareTo(y.CreatedDate);
}
orders.Sort(new OrderByCustomerNameComparer()); // sortowanie po IMIENIU klienta
orders.Sort(new OrderByDateComparer()); // sortowanie po DACIE
orders.Sort(); // the default CompareTo - by TotalAmount
The difference in short: you implement IComparable<T> on the class itself (one "natural" order), and you write IComparer<T> as a separate class when you need many, alternative ways of sorting the same type.
LINQ OrderBy - does NOT require IComparable on your class
This is a common conceptual trap, worth distinguishing:
// OrderBy in LINQ - works WITHOUT implementing IComparable on Order!
var sorted = orders.OrderBy(o => o.TotalAmount); // wymaga IComparable TYLKO na TYPIE KLUCZA (decimal), nie na Order
var sortedByName = orders.OrderBy(o => o.CustomerName); // string also has a built-in IComparable
OrderBy(keySelector) requires the type returned by the lambda (here: decimal, string) to implement IComparable - it does not require this of the whole Order class. That is why OrderBy works on any class, even with no IComparable implementation at all, as long as you pick a sort key that is itself comparable (which applies to practically all built-in types: int, string, DateTime, decimal).
orders.Sort(); // ❌ Compile error if Order does NOT implement IComparable<Order>
orders.OrderBy(o => o.TotalAmount); // ✅ ALWAYS works, regardless of whether Order implements IComparable
IComparable and the operators <, >, <=, >=
Implementing IComparable<T> does not automatically let you write order1 < order2 - to get that, you have to overload the operators separately:
public class Order : IComparable<Order>
{
public decimal TotalAmount { get; set; }
public int CompareTo(Order other) => TotalAmount.CompareTo(other?.TotalAmount ?? 0);
// Operatory to ODDZIELNA deklaracja - IComparable ich NIE daje "za darmo"
public static bool operator <(Order left, Order right) => left.CompareTo(right) < 0;
public static bool operator >(Order left, Order right) => left.CompareTo(right) > 0;
public static bool operator <=(Order left, Order right) => left.CompareTo(right) <= 0;
public static bool operator >=(Order left, Order right) => left.CompareTo(right) >= 0;
}
if (order1 < order2) { /* ... */ } // NOW it works, because we explicitly overloaded the operator
The non-generic IComparable (without <T>) - the historical version
It is worth knowing that there is also an older, non-generic version from the days before generics in .NET (C# 1.0):
public interface IComparable
{
int CompareTo(object obj); // takes "object", requires a cast inside
}
public class Order : IComparable
{
public int CompareTo(object obj)
{
if (obj is not Order other) throw new ArgumentException("The object must be of type Order");
return TotalAmount.CompareTo(other.TotalAmount);
}
}
Why the generic IComparable<T> is better: it avoids boxing (for structs - going back to the conversation about struct) and runtime casts - CompareTo(Order other) is checked by the compiler at compile time, while CompareTo(object obj) throws an exception at runtime if someone passes the wrong type. In modern code always implement the generic version (IComparable<T>); the non-generic one is kept mainly for compatibility with older code.
Summary - a concise interview answer
IComparable<T>defines the natural sort order of an object through theCompareTo()method, which returns a negative/zero/positive value depending on whether the object is smaller than, equal to (in terms of ordering, not identity!) or greater than the one being compared. Implementing this interface is required for the parameterlessList<T>.Sort()orSortedSet<T>to work at all. When you need many different ways of sorting the same type, you use (instead, or additionally) separate classes implementingIComparer<T>. LINQOrderBy(keySelector)does not requireIComparableon the whole class - only on the type of the key selected in the lambda, which is a common source of confusion when comparing these two sorting mechanisms.