Updated on
IComparable<T> gives a type its one default sort order, IComparer<T> puts a sort order in a separate class, and the Comparison<T> delegate is a sort order written as a method or a lambda. All three answer the same question about two objects: which one comes first?
In our own code, we implement IComparable<T> when a type has one natural order, like an employee’s Id, and we pass a lambda for every other one-off sort. IComparer<T> wins when an API accepts nothing else, such as the SortedSet<T> constructor, or when we reuse the same comparison in several places.
In C#, arrays of built-in types such as integers or strings support sorting out of the box. This is because int and string implement the IComparable<T> interface. However, what if we want to compare the custom objects that we create? In that case, we have to implement IComparable<T> ourselves, or supply the comparison from the outside with IComparer<T> or the Comparison<T> delegate.
Let’s start.
What Is the IComparable Interface in C#?
IComparable<T> is the interface a type implements to define its own default sort order. It has one method, CompareTo(), which compares the current instance with another object of the same type.
CompareTo() returns an integer. A negative value means the current instance comes first, a positive value means it comes after the other object, and zero means the two sit at the same position.
Once a class implements it, Array.Sort() and List<T>.Sort() sort its objects without any extra argument, and so do sorted collections such as SortedSet<T>. They find the comparison through Comparer<T>.Default.
Without it, those calls cannot compare our objects. Array.Sort() on a class that implements neither IComparable<T> nor the older, non-generic IComparable throws an InvalidOperationException with the message “Failed to compare two elements in the array.”
A class has room for exactly one CompareTo(), so it holds one order. We give it the order most of our code needs, such as employees by Id.
For instance, let’s consider that we have an Employee class with two properties:
public partial class Employee
{
public int Id { get; set; }
public string? Name { get; set; }
public Employee(int id, string? name)
{
Id = id;
Name = name;
}
}
Now let’s say that we want to add a default sorting capability for this class. We can do that by implementing the IComparable<T> interface.
While implementing the IComparable<T> interface, we need to define the CompareTo() method. This method compares the current instance with another object of the same type and returns an integer that indicates whether the current instance should be before, after, or at the same position as the other object.
Let’s implement sorting in such a way to order the employees based on their Id values:
public partial class Employee : IComparable<Employee>
{
public int Id { get; set; }
public string? Name { get; set; }
public Employee(int id, string? name)
{
Id = id;
Name = name;
}
public int CompareTo(Employee? otherEmployee)
{
return otherEmployee is null ? 1 : Id.CompareTo(otherEmployee.Id);
}
}
If the CompareTo() method returns a negative value, the current instance comes before the other object. On the other hand, if it returns a positive value, the current instance comes after the other object. Similarly, returning a zero indicates that the current instance and the other object should be at the same level.
Notice how our CompareTo() handles a null argument. It returns 1, which puts the current employee after the null one, so null employees end up at the front of a sorted array. We follow the same rule in every Id comparison we write in this article.
Now let’s test the functionality in the Program class:
var employees = new Employee[5]
{
new Employee(4, "John"),
new Employee(2, "Tom"),
new Employee(1, "Eric"),
new Employee(5, "Dan"),
new Employee(3, "Alen")
};
Console.WriteLine("The Employee Array:");
PrintEmployees(employees);
Array.Sort(employees);
Console.WriteLine($"{Environment.NewLine}Default Sorting:");
PrintEmployees(employees);
static void PrintEmployees(Employee[] employees)
{
foreach (var employee in employees)
{
Console.WriteLine(employee.Id + "\t\t" + employee.Name);
}
}
Let’s run the program and observe the output:
The Employee Array: 4 John 2 Tom 1 Eric 5 Dan 3 Alen Default Sorting: 1 Eric 2 Tom 3 Alen 4 John 5 Dan
While printing the employee array, we can notice that initially, the elements are in the order we add them. However, after calling the Array.Sort(), we can see that they are ordered based on their Ids.
In this example, we have implemented a default sorting in ascending order. For implementing the sorting in descending order, we just need to reverse the order of elements in the CompareTo() method. Similarly, even though we tried the example with an array, this works the same way with List<T>.Sort() and with sorted collections such as SortedSet<T>.
What Is the IComparer Interface in C#?
IComparer<T> is the interface for a separate comparer class. Its one method, Compare(), takes two objects of the same type and returns a negative number, zero or a positive number, the same way CompareTo() does.
The difference is where the code lives. IComparable<T> sits inside the class we sort, while a comparer sits outside it. That is why we can sort one type by several fields or in both directions, and why we can sort types we cannot change, such as classes from a library.
We pass the comparer as an argument: Array.Sort(array, comparer), List<T>.Sort(comparer), or OrderBy(keySelector, comparer) in LINQ.
Some APIs accept nothing else. SortedSet<T>, SortedDictionary<TKey, TValue> and List<T>.BinarySearch() take an IComparer<T> and have no overload for a delegate. When we already have a lambda, Comparer<T>.Create() turns it into a comparer that works with all of them.
We cover Comparer<T>.Create() and deriving from Comparer<T>, the abstract base class, in a separate article.
Using IComparer<T> is a two-step process. First, we need to declare a class that implements the IComparer<T> interface and implements the Compare() method. The Compare() method has to deal with null too. Microsoft Learn’s page for IComparer<T>.Compare() says that “a null reference is considered to be less than any reference that is not null.” So, our comparer puts null employees first, exactly like our CompareTo() does. Let’s create a class for implementing sorting by Id in ascending order:
public class SortByIdAscendingHelper : IComparer<Employee>
{
public int Compare(Employee? firstEmployee, Employee? secondEmployee)
{
if (firstEmployee is null)
{
return secondEmployee is null ? 0 : -1;
}
if (secondEmployee is null)
{
return 1;
}
return firstEmployee.Id.CompareTo(secondEmployee.Id);
}
}
The second step is to declare a method in the Employee class that returns an instance of the previous IComparer object:
public static IComparer<Employee> SortByIdAscending()
{
return new SortByIdAscendingHelper();
}
After that, we can supply this IComparer object as the second argument when we call the overloaded Array.Sort() method in the Program class:
Array.Sort(employees, Employee.SortByIdAscending());
Console.WriteLine($"{Environment.NewLine}Sorting by Id Ascending");
PrintEmployees(employees);
Now let’s run the application and test the results:
Sorting by Id Ascending 1 Eric 2 Tom 3 Alen 4 John 5 Dan
We can see that this sorts the Employee array based on ascending order of Id.
Returning 0 whenever one of the employees is null looks like a harmless shortcut, but don’t do it. It tells the sort that a null employee equals every other employee, and the result stops being sorted. When we tried that shortcut on the employees 4, null, 2, 1, null, 5, 3, Array.Sort() returned 4, null, 1, 2, null, 3, 5.
Similarly, we can define any number of IComparer objects that can sort the objects based on different fields and different orders. For instance, if we want to implement sorting by descending order of Id, we can create a new class with the same null checks:
public class SortByIdDescendingHelper : IComparer<Employee>
{
public int Compare(Employee? firstEmployee, Employee? secondEmployee)
{
if (firstEmployee is null)
{
return secondEmployee is null ? 0 : -1;
}
if (secondEmployee is null)
{
return 1;
}
return secondEmployee.Id.CompareTo(firstEmployee.Id);
}
}
Of course, we need to create a new method that returns an instance of the IComparer object:
public static IComparer<Employee> SortByIdDescending()
{
return new SortByIdDescendingHelper();
}
After that, we can use this IComparer object for sorting the Employee array:
Array.Sort(employees, Employee.SortByIdDescending());
Console.WriteLine($"{Environment.NewLine}Sorting by Id Descending");
PrintEmployees(employees);
This will sort the array in the descending order of Id:
Sorting by Id Descending 5 Dan 4 John 3 Alen 2 Tom 1 Eric
This way, we can implement any number of additional sorting capabilities for a class by creating different IComparer objects. We can create IComparer objects to sort not just arrays, but any type of collection.
What Is the Comparison Delegate in C#?
We can use the Comparison<T> delegate to implement a method that compares two objects of the same type:
public delegate int Comparison<in T>(T x, T y);
Here, T represents the type of objects to compare and the delegate has two parameters x and y that represent objects of the same type. It returns a signed integer value: when x is less than y the value is less than zero, and vice versa. If x equals y, it returns zero.
Like any delegate in C#, it can point to a static method, an instance method or a lambda expression.
Let’s implement a Comparison<T> delegate method in the Employee class to compare employees by Id in ascending order, with the same null rule as our comparer:
public static int CompareEmployeesByIdAscending(Employee? employee1, Employee? employee2)
{
if (employee1 is null)
{
return employee2 is null ? 0 : -1;
}
if (employee2 is null)
{
return 1;
}
return employee1.Id.CompareTo(employee2.Id);
}
We can use the Comparison<T> delegate for sorting both Arrays or Collections by passing it as an argument into the respective Sort() method.
In the Program class, let’s create the employee list and use the Comparison<T> delegate to sort it:
var employeeList = new List<Employee>
{
new Employee(4, "John"),
new Employee(2, "Tom"),
new Employee(1, "Eric"),
new Employee(5, "Dan"),
new Employee(3, "Alen")
};
employeeList.Sort(Employee.CompareEmployeesByIdAscending);
Console.WriteLine($"{Environment.NewLine}Sorting by Id Ascending using Comparison Delegate");
PrintEmployeeList(employeeList);
static void PrintEmployeeList(List<Employee> employees)
{
foreach (var employee in employees)
{
Console.WriteLine(employee.Id + "\t\t" + employee.Name);
}
}
If we look at the output, we can see that this sorts the employee list in the ascending order of Ids:
Sorting by Id Ascending using Comparison Delegate 1 Eric 2 Tom 3 Alen 4 John 5 Dan
Of course, if we want to sort in descending order, we just need to interchange the comparison order in the delegate method:
public static int CompareEmployeesByIdDescending(Employee? employee1, Employee? employee2)
{
if (employee1 is null)
{
return employee2 is null ? 0 : -1;
}
if (employee2 is null)
{
return 1;
}
return employee2.Id.CompareTo(employee1.Id);
}
When we pass it to employeeList.Sort() the same way, it sorts the employee list in the descending order of Ids:
Sorting by Id Descending using Comparison Delegate 5 Dan 4 John 3 Alen 2 Tom 1 Eric
It is possible to implement sorting based on different fields using the Comparison<T> delegate, and we don’t even need a named method for it. A lambda expression converts to Comparison<T> too, which makes it the shortest way to sort by another field. Let’s sort the same list by Name:
employeeList.Sort((x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal));
Console.WriteLine($"{Environment.NewLine}Sorting by Name using a Lambda Expression");
PrintEmployeeList(employeeList);
Now the employees come in alphabetical order:
Sorting by Name using a Lambda Expression 3 Alen 5 Dan 1 Eric 4 John 2 Tom
We use string.Compare() with StringComparison.Ordinal, so the order does not depend on the culture of the machine that runs the code. It also handles a null name for us and puts it first, which is the same rule as before.
When Should We Use IComparable, IComparer or the Comparison Delegate?
We use IComparable<T> when a type has one natural order that most code needs, such as employees by Id. It lives in the class, so every Array.Sort() and List<T>.Sort() call picks it up without an argument.
We use a Comparison<T> delegate, usually a lambda, for any other order we need in one place: by Name, by salary, in reverse. It is the shortest of the three, and it needs no new type.
IComparer<T> is the choice when the comparison has to be an object. That covers APIs that accept only a comparer, such as SortedSet<T>, comparisons we reuse across the code base, and comparers that carry settings, such as a sort direction or a culture.
All three follow the same rules. They return a negative number, zero or a positive number, and they treat null as smaller than any object. Two objects that compare as equal can end up in either order, because Array.Sort() is not a stable sort.
By implementing the IComparable interface, we are providing the capability to compare that object with other objects of the same class. As the name suggests, IComparable is more like saying “I’m Comparable”. For comparing objects using the IComparable interface, we have to implement the IComparable interface in that class. Furthermore, we can use the IComparable interface to add just one type of sorting capability to a class. We typically use this when we need to add a default sorting capability for a class. Once we implement this, we can sort arrays using the Array.Sort<T>(T[]) method, Lists using the List<T>.Sort() method, etc.Â
On the other hand, by implementing the IComparer interface, we are creating a comparer object which can compare any two instances of the same class. As the name suggests, IComparer is more like saying “I’m a Comparer”. For comparing objects using the IComparer interface, we don’t have to make any changes to that class, but we just need to create an external Comparer object. Furthermore, we can implement different types of sorting based on different fields and orders by creating the corresponding Comparer objects. Typically we use this when we want to add additional sorting capabilities to a class that may already have a default sorting. We just need to supply the Comparer while sorting arrays using the Sort<T>(T[], IComparer<T>) method overload, or while sorting the Lists using the Sort(IComparer<T>) method overload, etc. A comparer is also what a SortedSet<T> takes in its constructor when it should keep its items in an order other than the default one.
Comparison delegate is just another way to add sorting capabilities to a custom object. We can create a delegate method for comparing two objects of the same type just like how we would create a Comparer object. We can implement any number of sorting capabilities by creating different delegate methods. Later, we can supply the comparison delegate while sorting arrays using the Sort<T>(T[], Comparison<T>) method overload, or sorting Lists using the Sort(Comparison<T>) method overload, etc.
IComparable<T> | IComparer<T> | Comparison<T> |
|
|---|---|---|---|
| Where the code lives | Inside the class we sort | In a separate class | In a method or a lambda |
| Member | int CompareTo(T? other) | int Compare(T? x, T? y) | delegate int Comparison<in T>(T x, T y) |
| Orders per type | One | As many as we write | As many as we write |
| Changes the sorted class | Yes | No | No |
Array.Sort() / List<T>.Sort() | No argument needed | Pass the comparer | Pass the method or lambda |
SortedSet<T>, SortedDictionary<TKey, TValue>, BinarySearch() | Used as the default order | Accepted | Not accepted; wrap with Comparer<T>.Create() |
Allocations per Array.Sort() call (.NET 10, our run) | None | 64 B for the internal delegate, plus the comparer if we create one per call | None for a static method or a lambda that captures nothing |
| Best for | The one natural order | Reused comparisons and APIs that require a comparer | One-off sorts |
How Fast Are IComparable, IComparer and the Comparison Delegate?
Now let’s do some performance benchmarking of the IComparable interface, the IComparer interface, and the Comparison delegate and see how they compare against each other.
For comparing the performance, we are going to use Benchmarkdotnet, which is a powerful .NET library that can transform methods into benchmarks and track their performance. As explained in the linked article, let’s configure the BenchmarkDotNet library and design the benchmark class.
Array.Sort() reorders the array in place, and BenchmarkDotNet calls each benchmark method many times in a row. On a shared array, only the very first sort would see the employees out of order, so the class keeps a shuffled source and copies it before each sort:
[MemoryDiagnoser]
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByParams)]
public class ObjectComparisonBenchmark
{
private Employee[] _source = [];
private Employee[] _employees = [];
[Params(5, 1_000)]
public int Size { get; set; }
[GlobalSetup]
public void Setup()
{
var ids = Enumerable.Range(1, Size).ToArray();
new Random(42).Shuffle(ids);
_source = ids.Select(id => new Employee(id, $"Employee {id}")).ToArray();
_employees = new Employee[Size];
}
[Benchmark]
public Employee[] CompareUsingIComparable()
{
_source.CopyTo(_employees, 0);
Array.Sort(_employees);
return _employees;
}
[Benchmark]
public Employee[] CompareUsingIComparer()
{
_source.CopyTo(_employees, 0);
Array.Sort(_employees, Employee.SortByIdAscending());
return _employees;
}
[Benchmark]
public Employee[] CompareUsingComparisonDelegate()
{
_source.CopyTo(_employees, 0);
Array.Sort(_employees, Employee.CompareEmployeesByIdAscending);
return _employees;
}
}
BenchmarkDotNet calls Setup() for each benchmark method and size before timing begins. It creates Size employees and shuffles their ids with a fixed seed, so every run sorts the same order. We test two sizes: the five employees from our examples, and 1,000 employees.
The class goes in its own file in our console app. We add the BenchmarkDotNet package to the app, start the class file with using BenchmarkDotNet.Attributes;, using BenchmarkDotNet.Configs; and using BenchmarkDotNet.Order;, and call BenchmarkRunner.Run<ObjectComparisonBenchmark>(); from its Program.cs, after using BenchmarkDotNet.Running;. After we run the application in release configuration, it will do the performance benchmarking and print the results:
| Method | Size | Mean | Error | StdDev | Gen0 | Allocated | |------------------------------- |----- |-------------:|-----------:|-----------:|-------:|----------:| | CompareUsingIComparable | 5 | 63.85 ns | 0.237 ns | 0.198 ns | - | - | | CompareUsingComparisonDelegate | 5 | 73.51 ns | 1.333 ns | 1.181 ns | - | - | | CompareUsingIComparer | 5 | 79.67 ns | 0.569 ns | 0.444 ns | 0.0105 | 88 B | | | | | | | | | | CompareUsingIComparer | 1000 | 54,505.95 ns | 475.577 ns | 444.855 ns | - | 88 B | | CompareUsingIComparable | 1000 | 65,732.89 ns | 540.171 ns | 421.730 ns | - | - | | CompareUsingComparisonDelegate | 1000 | 73,290.41 ns | 107.549 ns | 95.339 ns | - | - |
With five employees, IComparable<T> is the fastest, the Comparison<T> delegate takes about 15 percent longer, and IComparer<T> is the slowest. It is also the only one of the three that allocates memory: 88 bytes per call.
Those 88 bytes are two objects. Employee.SortByIdAscending() creates a new comparer on every call, and Array.Sort() wraps the comparer’s Compare() method in a delegate before it starts sorting. If we keep one comparer instance in a static field, the first allocation goes away, but the delegate stays.
The delegate column shows no allocation because of the compiler. Since C# 11, the compiler caches the delegate it creates for a static method like Employee.CompareEmployeesByIdAscending, instead of creating a new one on every call.
With 1,000 employees, the comparisons themselves take almost all of the time, and the order changes. IComparer<T> comes first, IComparable<T> takes about a fifth longer, and the Comparison<T> delegate about a third longer. These gaps are many times larger than the margins of error.
In practice, none of these differences should decide which approach we use. Up to 20 nanoseconds or microseconds and 88 bytes per sort matter only inside a hot loop, so we choose by where the comparison belongs.
Conclusion
We’ve learned how the IComparable interface, the IComparer interface and the Comparison delegate each define a sort order, and how they compare against each other. IComparable<T> holds a type’s default order, IComparer<T> is the tool for when the comparison has to be an object, and a lambda covers the rest. Whichever one we pick, it returns the same kind of result and puts nulls first.
When the next step is sorting a list by one of its properties, our article on sorting a list by a property compares List<T>.Sort() with LINQ’s OrderBy(), including why only OrderBy() keeps equal items in their original order.
Tested with .NET 10.0.10, BenchmarkDotNet 0.15.8 and xUnit 2.9.3.







Hi!
Sorry to say that, but I think there are some issues with this article, making the benchmarks not so reliable.
First, the implementations are not optimal. You can improve them by using generic interfaces
IComparer<Employee>andIComparable<Employee>and fix a few issues around the way you handle the nullability.Then the
Countin the benchmark should change the size of the array, not how many times the same array is sorted. If you just sort the same array 10, 100 or 1000 times, it is clear that the Processing time + used memory will juste scale linearly.By fixing a few details in the implementation, IComparable becomes the fastest solution and with no memory allocation at all
public int CompareTo(Employee? employee) { return employee is null ? 1 : Id.CompareTo(employee.Id); }Hey,
Thank you for bringing this to our notice. We’ll check that and replace the examples with the generic interfaces and modify the benchmarks as well. Cheers!
We have updated the article. Once again thanks for pointing this out!
You’re welcome 🙂
I think there is still a small error just after the benchmark results. This should probably be removed