CodeGym /Courses /C# SELF /Interface IComparable<T>

Interface IComparable<T>

C# SELF
Level 30, Lesson 0
Available

1. Introduction

Imagine you ask your friend to put books on shelves. If these are books with numbers on the spines (1, 2, 3…), your friend will do it easily: "Okay, 1 goes before 2, 2 before 3." That's the natural order of numbers (in order). Same thing if the books have titles starting with "A", "B", "C"—your friend will put them in alphabetical order. That's also the "natural" order for strings (alphabetical).

But what if the books only have the authors' last names on the spines? And you say: "Put them in order." Your friend will ask: "What order? By last name? By year published? By number of pages?" That's where the problem starts. For your unique entities, there's no obvious natural order.

Same thing in programming. When we try to sort a list of integers List<int>, C# knows exactly what to do. For List<string> it also works, using lexicographical (alphabetical) order. But if we have a List<Student>, where each Student is an object with a name, last name, age, ID, and a bunch of other stuff, C# gets confused. It doesn't know which property to use to compare two students. By name? By ID? By GPA? That's exactly the problem we ran into in the "Sorting Collections" lecture, when List<T>.Sort() threw an error when we tried to sort a collection of custom types.

To solve this puzzle, we need to give C# a clear instruction on how to compare our objects. That's what the IComparable<T> interface is for.

2. The IComparable<T> Interface

So, to teach our objects to "know" their place relative to other objects of the same type, we use the IComparable<T> interface. It's a contract. When your class or struct implements this interface, you're basically telling the compiler: "Hey! My objects can be compared to each other, and here's how you do it."

How does it work?

The IComparable<T> interface defines just one method:

public interface IComparable<in T>
{
    int CompareTo(T other);
}

This method takes an object of type T (same type as the current object) and should return:

  • a negative number (< 0) if the current object is "less than" the one being compared;
  • zero (0) if they're "equal" (for sorting purposes);
  • a positive number (> 0) if the current object is "greater".

Basically, it's like judges at a competition, say, in a boxing match: if you performed better, you win the round and get more points; if you did worse, you get less; if it was a tie, the score is the same. Only here, instead of judges, it's just a signed number.

Why this way?

Sorting methods (like List<T>.Sort()) call CompareTo on list elements to figure out who goes first and who goes after. If your class implements this interface—it can be sorted!

3. Practice

Let's say we have a user class (User):

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Let's try to sort a list of users:

List<User> users = new List<User>
{
    new User { Name = "Sergey", Age = 31 },
    new User { Name = "Maria", Age = 22 },
    new User { Name = "Anton", Age = 27 }
};

users.Sort(); // BOOM! InvalidOperationException

You get an error: "At least one object must implement IComparable".

Fixing it: implement IComparable<User>

Let's add the interface to our class. For starters, let's sort by age—from youngest to oldest:

public class User : IComparable<User>
{
    public string Name { get; set; }
    public int Age { get; set; }

    public int CompareTo(User other)
    {
        // Safety check: if other == null, our user is "greater"
        if (other == null) return 1;
        return this.Age.CompareTo(other.Age); // sort by age
    }
}

Now let's make a list, call users.Sort(); and print the result to the console:

List<User> users = new List<User>
{
    new User { Name = "Sergey", Age = 31 },
    new User { Name = "Maria", Age = 22 },
    new User { Name = "Anton", Age = 27 }
};

// Sort by age (uses CompareTo)
users.Sort();

// Print sorted users
foreach (User user in users)
{
    Console.WriteLine($"{user.Name}, {user.Age}");
}

The list will be sorted by age:

Maria, 22
Anton, 27
Sergey, 31

Visualization: before and after

Name Age
Sergey 31
Maria 22
Anton 27

After sorting:

Name Age
Maria 22
Anton 27
Sergey 31

4. Important details and common mistakes

Guard against null

Inside CompareTo it's super important to check that other isn't null. If you skip this, your object might get a NullReferenceException—and those are as sneaky as bugs right before a release. Usually, if the compared object is null, it's standard to say the current one is "greater":

public int CompareTo(User other)
{
    if (other == null) return 1;
    // ...
}

Keep it transitive

If A < B and B < C, then A should be < C. If you break this rule, sorting will act unpredictably (which is fun, but totally wrong!).

If you need to sort by multiple fields

Say you want to sort by age first, but if two users are the same age, sort them by name alphabetically. Here's how you do it:

public int CompareTo(User other)
{
    if (other == null) return 1;

    int ageCompare = this.Age.CompareTo(other.Age);
    if (ageCompare != 0) return ageCompare;

    // If ages are equal—compare by name
    return this.Name.CompareTo(other.Name);
}

5. Sorting: now with your own objects

Everything List<int> can do—your class can do too

Now you can use any method that needs comparison: Sort, BinarySearch, even inserting into sorted collections (like SortedSet<T>).

users.Sort();
// users is now sorted by age (and by name if ages are equal)

Example in a course app context

Say you already built an app to keep track of users. Now we can add a "natural" sort order to them right in the existing code. Here's what it looks like:

// Our User class already implements IComparable<User>

List<User> users = new List<User>
{
    new User { Name = "Ivan", Age = 45 },
    new User { Name = "Galina", Age = 27 },
    new User { Name = "Yuriy", Age = 27 }
};

// Sort by age, then by name
users.Sort();
foreach (var u in users)
{
    Console.WriteLine($"{u.Name} - {u.Age}");
}

Result:

Galina - 27
Yuriy - 27
Ivan - 45

Galina and Yuriy are the same age, so sorting by name when ages are equal.

6. How CompareTo works: the hard math

Let's highlight the return value standard one more time:

  • Negative number (for example, -1): current object comes before the compared one.
  • Zero: considered equal for sorting.
  • Positive number (for example, 1): current object comes after the compared one.

Built-in types (like Age.CompareTo(other.Age)) already follow this standard, always returning -1, 0, or 1.

Return value table for CompareTo

Return value What does it mean? Example
< 0 Less (comes before)
20.CompareTo(21): -1
0 Equal
23.CompareTo(23): 0
> 0 Greater (comes after)
42.CompareTo(15): 1

7. Multi-field sorting: combining fields

Sometimes you need more complex sorting: for example, by last name, first name, and age. Using the same trick, you can compare fields one after another:

public class Student : IComparable<Student>
{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public int Grade { get; set; }

    public int CompareTo(Student other)
    {
        if (other == null) return 1;
        int lastNameCompare = this.LastName.CompareTo(other.LastName);
        if (lastNameCompare != 0) return lastNameCompare;
        int firstNameCompare = this.FirstName.CompareTo(other.FirstName);
        if (firstNameCompare != 0) return firstNameCompare;
        return this.Grade.CompareTo(other.Grade);
    }
}

8. When you should NOT implement IComparable<T>

A real-life (programmer) situation: if your object doesn't have a "natural" sort order, it's better NOT to implement IComparable<T>. For example, if you have a Point class, and you don't know—should you sort by X, by Y, or by distance from the origin—it's better to pass in a comparer from the outside using a comparison function (IComparer<T>). We'll talk about that in the next lecture.

2
Task
C# SELF, level 30, lesson 0
Locked
Implementing the IComparable interface for comparison by a single field
Implementing the IComparable interface for comparison by a single field
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION