0Pricing
C# Academy · Lesson

Implementing IComparable

Define a natural sort order with CompareTo.

Ordering With IComparable<T>

IComparable<T> defines a natural order for a type through a single method, CompareTo. Once implemented, your type can be sorted by Array.Sort, List.Sort, and ordered collections.

The CompareTo Contract

CompareTo returns a negative number if this instance is less than the other, zero if equal, and a positive number if greater. Comparing the underlying values often implements this directly.

using System;

public struct Weight : IComparable<Weight>
{
    public int Grams;
    public Weight(int g) { Grams = g; }

    public int CompareTo(Weight other) => Grams.CompareTo(other.Grams);

    public override string ToString() => Grams + "g";
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine(new Weight(100).CompareTo(new Weight(200)));
        Console.WriteLine(new Weight(200).CompareTo(new Weight(200)));
        Console.WriteLine(new Weight(300).CompareTo(new Weight(200)));
    }
}

All lessons in this course

  1. Implementing IEquatable
  2. Overriding GetHashCode
  3. Implementing IComparable
  4. IComparer for Custom Sorting
← Back to C# Academy