C# IComparable
last modified November 6, 2026
In this article we show how to compare values in C# with the
IComparable interface.
C# IComparable interface
The IComparable<T> interface defines a generalized
type-specific comparison method that a value type or class implements to order
or sort its instances. There is also an older, non-generic
IComparable interface, whose method takes an object.
New code should implement the generic version, which avoids casting and
boxing.
The IComparable is implemented by types whose values have a
natural order. The interface requires the CompareTo method to be
implemented. The implemented method is automatically called by methods such as
Array.Sort and List.Sort, by LINQ's
Order, Min, and Max, and by sorted
collections such as SortedSet.
The CompareTo method returns an integer:
- a negative value if the current instance precedes the other one
- zero if both instances have the same position in the sort order
- a positive value if the current instance follows the other one
The interface is used by types that the programmer has control over; in other words, by code they have written. If the code is provided by someone else, or if we need several different orderings, we use the IComparer interface instead.
C# built-in comparable types
Numbers, strings, dates, and many other built-in types implement
IComparable<T>.
Console.WriteLine(3.CompareTo(7));
Console.WriteLine(7.CompareTo(3));
Console.WriteLine(5.CompareTo(5));
Console.WriteLine("apple".CompareTo("banana"));
Console.WriteLine(new DateOnly(2026, 1, 1).CompareTo(new DateOnly(2025, 1, 1)));
IComparable<double> d = 2.5;
Console.WriteLine(d.CompareTo(1.5));
We call the CompareTo method on several built-in types. Only the
sign of the result is meaningful; we must not rely on the actual value being
-1 or 1.
$ dotnet run -1 1 0 -1 1 1
C# IComparable example
In the following example, we sort a list of employees.
List<Employee> employees =
[
new("John Doe", 1230),
new("Lucy Novak", 670),
new("Robin Brown", 2300),
new("Joe Draker", 1190),
new("Janet Doe", 980)
];
employees.Sort();
employees.ForEach(Console.WriteLine);
Console.WriteLine("---------------------------");
employees.Reverse();
employees.ForEach(Console.WriteLine);
record Employee(string Name, int Salary) : IComparable<Employee>
{
public int CompareTo(Employee? other)
{
if (other is null) return 1;
if (Salary < other.Salary)
{
return -1;
}
else if (Salary > other.Salary)
{
return 1;
}
else
{
return 0;
}
}
}
In the example, we provide an implementation of the CompareTo
method of the Employee record. The record implements the
IComparable<Employee> interface.
if (Salary < other.Salary)
{
return -1;
}
else if (Salary > other.Salary)
{
return 1;
}
else
{
return 0;
}
The implementation of the CompareTo method sorts the employees
by their salary in ascending order. The whole if/else
chain could be replaced with return Salary.CompareTo(other.Salary);.
if (other is null) return 1;
By common definition, the current object is greater than
null.
employees.Sort();
We sort the list. The method takes the implemented CompareTo
method into account when sorting.
employees.Reverse();
The Reverse method reverses the order of the elements. Applied to
a sorted list, it gives us the descending order.
$ dotnet run
Employee { Name = Lucy Novak, Salary = 670 }
Employee { Name = Janet Doe, Salary = 980 }
Employee { Name = Joe Draker, Salary = 1190 }
Employee { Name = John Doe, Salary = 1230 }
Employee { Name = Robin Brown, Salary = 2300 }
---------------------------
Employee { Name = Robin Brown, Salary = 2300 }
Employee { Name = John Doe, Salary = 1230 }
Employee { Name = Joe Draker, Salary = 1190 }
Employee { Name = Janet Doe, Salary = 980 }
Employee { Name = Lucy Novak, Salary = 670 }
C# IComparable sorting strings
In the following example, we sort an array of users by their occupation.
User[] users =
[
new("Robin", "bookseller"),
new("John", "gardener"),
new("John", "writer"),
new("Janet", "teacher"),
new("Andrew", "driver"),
new("Lucy", "accountant")
];
Array.Sort(users);
foreach (var user in users)
{
Console.WriteLine(user);
}
Console.WriteLine("------------------------------");
Array.Reverse(users);
foreach (var user in users)
{
Console.WriteLine(user);
}
record User(string Name, string Occupation) : IComparable<User>
{
public int CompareTo(User? other)
{
if (other is null) return 1;
return string.Compare(Occupation, other.Occupation, StringComparison.Ordinal);
}
}
The example sorts an array of users in ascending and descending order.
return string.Compare(Occupation, other.Occupation, StringComparison.Ordinal);
The method sorts by the occupation. The string.CompareTo method
uses the current culture's rules, so the result may differ between machines.
For a predictable order, we pass a StringComparison value
explicitly.
Array.Sort(users);
We sort the users in ascending order.
Array.Reverse(users);
We reverse the sorted array to get the descending order.
$ dotnet run
User { Name = Lucy, Occupation = accountant }
User { Name = Robin, Occupation = bookseller }
User { Name = Andrew, Occupation = driver }
User { Name = John, Occupation = gardener }
User { Name = Janet, Occupation = teacher }
User { Name = John, Occupation = writer }
------------------------------
User { Name = John, Occupation = writer }
User { Name = Janet, Occupation = teacher }
User { Name = John, Occupation = gardener }
User { Name = Andrew, Occupation = driver }
User { Name = Robin, Occupation = bookseller }
User { Name = Lucy, Occupation = accountant }
C# IComparable multiple fields
In the following example, we compare by two fields.
List<User> users =
[
new("Robin", "bookseller"),
new("Simon", "teacher"),
new("Arnold", "teacher"),
new("John", "gardener"),
new("Adam", "gardener"),
new("Peter", "gardener"),
new("John", "writer"),
new("Janet", "teacher"),
new("Andrew", "driver"),
new("Lucy", "accountant"),
new("Michael", "teacher")
];
users.Sort();
foreach (var user in users)
{
Console.WriteLine(user);
}
record User(string Name, string Occupation) : IComparable<User>
{
public int CompareTo(User? other)
{
if (other is null) return 1;
int res = string.Compare(Occupation, other.Occupation, StringComparison.Ordinal);
if (res == 0)
{
res = string.Compare(other.Name, Name, StringComparison.Ordinal);
}
return res;
}
}
We have users with the same occupation. In such a case, we then compare their names.
int res = string.Compare(Occupation, other.Occupation, StringComparison.Ordinal);
if (res == 0)
{
res = string.Compare(other.Name, Name, StringComparison.Ordinal);
}
First, we compare users by their Occupation fields. If they are
equal, we compare their Name fields. Since the arguments of the
second comparison are swapped, the names are sorted in descending order.
$ dotnet run
User { Name = Lucy, Occupation = accountant }
User { Name = Robin, Occupation = bookseller }
User { Name = Andrew, Occupation = driver }
User { Name = Peter, Occupation = gardener }
User { Name = John, Occupation = gardener }
User { Name = Adam, Occupation = gardener }
User { Name = Simon, Occupation = teacher }
User { Name = Michael, Occupation = teacher }
User { Name = Janet, Occupation = teacher }
User { Name = Arnold, Occupation = teacher }
User { Name = John, Occupation = writer }
C# IComparable with LINQ and sorted collections
Once a type implements IComparable<T>, it works with all
the APIs that need ordering.
List<Version> versions =
[
new(2, 1, 0),
new(1, 9, 12),
new(2, 0, 5),
new(1, 10, 0),
];
Console.WriteLine($"Min: {versions.Min()}");
Console.WriteLine($"Max: {versions.Max()}");
Console.WriteLine(string.Join(", ", versions.Order()));
Console.WriteLine(string.Join(", ", versions.OrderDescending()));
var sorted = new SortedSet<Version>(versions);
Console.WriteLine(sorted.First());
record Version(int Major, int Minor, int Patch) : IComparable<Version>
{
public int CompareTo(Version? other)
{
if (other is null) return 1;
int res = Major.CompareTo(other.Major);
if (res != 0) return res;
res = Minor.CompareTo(other.Minor);
if (res != 0) return res;
return Patch.CompareTo(other.Patch);
}
public override string ToString() => $"{Major}.{Minor}.{Patch}";
}
We define a Version record, which compares versions by their
major, minor, and patch numbers. Note that version 1.10.0 follows 1.9.12; a
plain string comparison would put them in the wrong order.
Console.WriteLine(string.Join(", ", versions.Order()));
Console.WriteLine(string.Join(", ", versions.OrderDescending()));
The Order and OrderDescending methods, available
since .NET 7, sort elements by their natural order. Unlike
List.Sort, they do not modify the source list and they are
stable; elements that compare as equal keep their original order.
var sorted = new SortedSet<Version>(versions);
The SortedSet keeps its elements ordered with the
CompareTo method.
$ dotnet run Min: 1.9.12 Max: 2.1.0 1.9.12, 1.10.0, 2.0.5, 2.1.0 2.1.0, 2.0.5, 1.10.0, 1.9.12 1.9.12
C# IComparable and comparison operators
Implementing IComparable<T> does not give a type the
< and > operators. We can define them
ourselves on top of CompareTo.
var m1 = new Money(12.50m);
var m2 = new Money(7.20m);
var m3 = new Money(12.50m);
Console.WriteLine(m1 > m2);
Console.WriteLine(m1 <= m3);
Console.WriteLine(m2 < m3);
Console.WriteLine(m1 == m3);
readonly record struct Money(decimal Amount) : IComparable<Money>
{
public int CompareTo(Money other) => Amount.CompareTo(other.Amount);
public static bool operator <(Money a, Money b) => a.CompareTo(b) < 0;
public static bool operator >(Money a, Money b) => a.CompareTo(b) > 0;
public static bool operator <=(Money a, Money b) => a.CompareTo(b) <= 0;
public static bool operator >=(Money a, Money b) => a.CompareTo(b) >= 0;
}
The Money type is a record struct with comparison operators.
The operators delegate to the CompareTo method, so the logic is
defined only once. The == operator is generated by the record.
$ dotnet run True True True True
C# IComparable generic constraint
The where T : IComparable<T> constraint allows a generic
method to compare values of any comparable type.
Console.WriteLine(Largest([3, 9, 1, 7]));
Console.WriteLine(Largest(["sky", "war", "cup", "atom"]));
Console.WriteLine(Clamp(15, 0, 10));
Console.WriteLine(Clamp('m', 'a', 'f'));
static T Largest<T>(T[] vals) where T : IComparable<T>
{
T max = vals[0];
foreach (var e in vals[1..])
{
if (e.CompareTo(max) > 0)
{
max = e;
}
}
return max;
}
static T Clamp<T>(T val, T min, T max) where T : IComparable<T>
{
if (val.CompareTo(min) < 0) return min;
if (val.CompareTo(max) > 0) return max;
return val;
}
We define the Largest and Clamp methods, which work
with integers, strings, characters, or any other type implementing the
interface.
$ dotnet run 9 war 10 f
C# sorting types without IComparable
If we try to sort elements of a type that has no natural order, the sort method fails at runtime.
List<Point> points = [new(3, 4), new(1, 2)];
try
{
points.Sort();
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.InnerException?.Message);
}
record Point(int X, int Y);
The Point record does not implement IComparable. The
Sort method throws an InvalidOperationException
whose inner exception explains the cause. To sort such values, we either
implement the interface, or pass a comparer or a comparison delegate to the
sort method.
$ dotnet run Failed to compare two elements in the array. At least one object must implement IComparable.
Source
In this article we have used the IComparable interface to sort data
in C#.
Author
List all C# tutorials.