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

IComparable

In this page:

  1. IComparable

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}");
        }
    }
}
🔒

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.