IComparable Interface

public interface IComparable<in T>

Represents a method that compares the current instance with another object of the same type.

Remarks

The IComparable interface should be implemented by any class that needs to establish a default sorting order for its type. The CompareTo method allows objects to be compared to each other without having to specify a separate comparer object.

For example, a Product class might implement IComparable to allow sorting products by name, price, or ID.

Members

Name Description
CompareTo(T other) Compares the current instance with another object of the same type.

Implementations

The IComparable interface is implemented by many built-in .NET types, including:

  • System.String
  • System.Int32
  • System.DateTime
  • System.Version

Example

The following example demonstrates how to implement the IComparable interface in a custom class.


using System;

public class Book : IComparable<Book>
{
    public string Title { get; set; }
    public string Author { get; set; }
    public int PublicationYear { get; set; }

    public int CompareTo(Book other)
    {
        if (other == null)
        {
            return 1; // Current instance is greater than null
        }

        // Compare by PublicationYear
        int yearComparison = this.PublicationYear.CompareTo(other.PublicationYear);
        if (yearComparison != 0)
        {
            return yearComparison;
        }

        // If years are the same, compare by Title
        return this.Title.CompareTo(other.Title);
    }

    public override string ToString()
    {
        return $"{Title} ({Author}, {PublicationYear})";
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        Book book1 = new Book { Title = "The Hitchhiker's Guide to the Galaxy", Author = "Douglas Adams", PublicationYear = 1979 };
        Book book2 = new Book { Title = "Pride and Prejudice", Author = "Jane Austen", PublicationYear = 1813 };
        Book book3 = new Book { Title = "Dune", Author = "Frank Herbert", PublicationYear = 1965 };
        Book book4 = new Book { Title = "The Martian", Author = "Andy Weir", PublicationYear = 2011 };
        Book book5 = new Book { Title = "Foundation", Author = "Isaac Asimov", PublicationYear = 1951 };

        System.Collections.Generic.List<Book> books = new System.Collections.Generic.List<Book> { book1, book2, book3, book4, book5 };

        Console.WriteLine("Before sorting:");
        foreach (var book in books)
        {
            Console.WriteLine(book);
        }

        books.Sort(); // Uses the IComparable implementation

        Console.WriteLine("\nAfter sorting by publication year (and title if year is same):");
        foreach (var book in books)
        {
            Console.WriteLine(book);
        }
    }
}