In C#, IComparable is an interface that says "objects of this type can be compared with each other." It has one method, CompareTo().
Types like int, string, and DateTime already implement it. That is why Array.Sort() and List.Sort() can sort them. Implement it on your own class to make it sortable too.
Syntax
The generic version IComparable<T> is the one you will use most.
C#
public interface IComparable<T>
{
int CompareTo(T? other);
}
Call
What it does
a.CompareTo(b)
Returns a negative number, zero, or a positive number.
Numbers and strings already know how to compare themselves.
C#
using System;
class Program {
static void Main() {
Console.WriteLine(Math.Sign(5.CompareTo(10)));
Console.WriteLine(Math.Sign(10.CompareTo(10)));
Console.WriteLine(Math.Sign("pear".CompareTo("apple")));
}
}
Output
-1
0
1
How It Works
5 vs 10. 5 comes first, so the result is negative.
10 vs 10. Equal values give zero.
pear vs apple."pear" comes later in the alphabet, so the result is positive.
Example 2 — Make Your Own Class Sortable
Sort students by age by implementing IComparable<Student>.
C#
using System;
using System.Collections.Generic;
class Student : IComparable<Student> {
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(Student other) {
return Age.CompareTo(other.Age);
}
}
class Program {
static void Main() {
var list = new List<Student> {
new Student { Name = "Mia", Age = 22 },
new Student { Name = "Leo", Age = 19 },
new Student { Name = "Zoe", Age = 20 }
};
list.Sort();
foreach (Student s in list) {
Console.WriteLine($"{s.Name} ({s.Age})");
}
}
}
Output
Leo (19)
Zoe (20)
Mia (22)
How It Works
Implement the interface.Student promises to provide CompareTo().
Compare one field. We reuse int.CompareTo() on Age.
Sort() uses it. The list is now in order from youngest to oldest.
Example 3 — Use IComparable in a Generic Method
One method that finds the larger of two values, for any comparable type.
C#
using System;
class Program {
static T Max<T>(T a, T b) where T : IComparable<T> {
return a.CompareTo(b) >= 0 ? a : b;
}
static void Main() {
Console.WriteLine(Max(3, 9));
Console.WriteLine(Max("apple", "pear"));
}
}
Output
9
pear
How It Works
Constraint.where T : IComparable<T> guarantees CompareTo() exists.
One method, many types. It works for numbers and strings alike.
Check the result. A value of zero or more means a is not smaller than b.
Frequently Asked Questions
It is an interface with one method, CompareTo(), that lets objects of a type be compared and sorted.
A negative number if this object is smaller, zero if equal, and a positive number if it is larger.
IComparable<T> is type-safe and avoids casting. Prefer it in new code.
Sort() needs to know which of two items comes first. It calls CompareTo() to find out.
Pass a Comparison delegate or an IComparer to Sort() instead of changing CompareTo().