0
0
CsharpHow-ToBeginner · 4 min read

How to Use IComparable in C# for Custom Sorting

In C#, implement the IComparable interface in your class to define how objects should be compared and sorted. Override the CompareTo method to return a value indicating the order between the current object and another. This allows sorting methods like Array.Sort or List.Sort to work with your custom objects.
📐

Syntax

To use IComparable, your class must implement the interface and define the CompareTo method. This method takes an object of the same type and returns an integer:

  • Less than 0: current object is less than the other
  • 0: both objects are equal
  • Greater than 0: current object is greater than the other
csharp
public class MyClass : IComparable<MyClass>
{
    public int CompareTo(MyClass other)
    {
        // return negative, zero, or positive
    }
}
💻

Example

This example shows a Person class that implements IComparable<Person> to sort people by their age.

csharp
using System;
using System.Collections.Generic;

public class Person : IComparable<Person>
{
    public string Name { get; set; }
    public int Age { get; set; }

    public int CompareTo(Person other)
    {
        if (other == null) return 1;
        return this.Age.CompareTo(other.Age);
    }
}

public class Program
{
    public static void Main()
    {
        List<Person> people = new List<Person>
        {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 25 },
            new Person { Name = "Charlie", Age = 35 }
        };

        people.Sort();

        foreach (var person in people)
        {
            Console.WriteLine($"{person.Name} - {person.Age}");
        }
    }
}
Output
Bob - 25 Alice - 30 Charlie - 35
⚠️

Common Pitfalls

Common mistakes when using IComparable include:

  • Not handling null values in CompareTo, which can cause exceptions.
  • Returning incorrect values (not negative, zero, or positive) which breaks sorting logic.
  • Implementing IComparable but forgetting to use generic IComparable<T> for type safety.
  • Not overriding Equals and GetHashCode consistently with CompareTo.

Example of a wrong and right CompareTo:

csharp
public class WrongPerson : IComparable<WrongPerson>
{
    public int Age { get; set; }

    // Wrong: returns 1 or 0 only, missing negative values
    public int CompareTo(WrongPerson other)
    {
        if (other == null) return 1;
        if (this.Age > other.Age) return 1;
        return 0;
    }
}

public class RightPerson : IComparable<RightPerson>
{
    public int Age { get; set; }

    public int CompareTo(RightPerson other)
    {
        if (other == null) return 1;
        return this.Age.CompareTo(other.Age);
    }
}
📊

Quick Reference

  • IComparable<T>: Use generic interface for type safety.
  • CompareTo(T other): Return <0, 0, or >0 to indicate order.
  • Handle null: Always check if other is null.
  • Consistent logic: Ensure CompareTo, Equals, and GetHashCode agree.
  • Use with sorting: Works with List.Sort() and Array.Sort().

Key Takeaways

Implement IComparable and define CompareTo to enable custom sorting.
Return negative, zero, or positive values correctly to indicate order.
Always check for null in CompareTo to avoid exceptions.
Use generic IComparable for type safety instead of non-generic IComparable.
Ensure CompareTo logic matches Equals and GetHashCode for consistency.