← Back to C# Course | Chapter 8: Interfaces | Lesson 5 of 6

IComparable

IComparable lets objects be compared so they can be sorted, like teaching kids how to line up by height. An object learns to say whether it comes before or after another.

In this page:

  1. IComparable
Syntax
csharp
class ClassName : IComparable<ClassName>
{
    public int CompareTo(ClassName other)
    {
        return this.Value.CompareTo(other.Value);   // <0, 0, >0
    }
}

IComparable

IComparable<T> defines a single method, CompareTo, that lets objects define their own natural ordering.

Implementing it allows a type to be sorted with Array.Sort or List<T>.Sort without any extra comparer. CompareTo returns negative, zero, or positive to indicate less-than, equal, or greater-than.

Note: Implement IComparable<T> whenever a type has an obvious natural sort order, like a numeric score.

Example: IComparable

markup
using System;
using System.Collections.Generic;

class Player : IComparable<Player>
{
    public string Name;
    public int Score;

    public Player(string name, int score)
    {
        Name = name;
        Score = score;
    }

    public int CompareTo(Player other)
    {
        return Score.CompareTo(other.Score);
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<Player> players = new List<Player>
        {
            new Player("Ana", 50),
            new Player("Ben", 90),
            new Player("Cid", 20),
        };

        players.Sort();

        foreach (Player p in players)
        {
            Console.WriteLine($"{p.Name}: {p.Score}");
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting to declare : IComparable<Player> on the class, so list.Sort() throws an InvalidOperationException because the items cannot be compared.
  2. Returning the wrong sign from CompareTo, so the list sorts in the opposite order; it should return a negative number if this object comes first, zero if equal, and a positive number otherwise.
  3. Implementing CompareTo as Score - other.Score, which can overflow for large values and give a wrong result; use Score.CompareTo(other.Score) instead.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.