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:
Syntax
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
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}");
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Forgetting to declare
: IComparable<Player>on the class, solist.Sort()throws anInvalidOperationExceptionbecause the items cannot be compared. - 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. - Implementing
CompareToasScore - other.Score, which can overflow for large values and give a wrong result; useScore.CompareTo(other.Score)instead.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: