Understanding the IComparable in C#

What is IComparable in C#?

The “IComparable” is an interface that defines a single method for comparing objects of the same type and allows us to sort them based on a specific field. Below we can see the “IComparable” interface declaration:

When you implement the IComparable interface in a class, you are essentially saying that objects of that class can be compared with each other using a predefined criterion. This criterion is defined by the CompareTo method, which must be implemented as part of the interface contract.

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

Note. As we can see, this interface has only a single method called “CompareTo” which returns:

  • “1” if object a is bigger than object b
  • “-1” if object a is smaller than object b
  • “0” if both objects are equal

Student class

Consider the class below. Let's assume we have a group of objects from this class, and we want to sort them based on their RollNo.

class Student
{
    public string Name { get; set; }
    public int RollNo { get; set; }
    public string Standard { get; set; }
    public string Division { get; set; }

    // Constructor
    public Student(string name, int rollNo, string standard, string division)
    {
        Name = name;
        RollNo = rollNo;
        Standard = standard;
        Division = division;
    }
}

How to Use IComparable in C#?

using System;

class Student : IComparable<Student>
{
    public string Name { get; set; }
    public int RollNo { get; set; }
    public string Standard { get; set; }
    public string Division { get; set; }

    // Constructor
    public Student(string name, int rollNo, string standard, string division)
    {
        Name = name;
        RollNo = rollNo;
        Standard = standard;
        Division = division;
    }

    // Implement the CompareTo method from IComparable<Student>
    public int CompareTo(Student other)
    {
        if (other == null)
            return 1;

        // Compare based on RollNo
        return RollNo.CompareTo(other.RollNo);
    }
}
Student student1 = new Student("Alice", 101, "10th", "A");
Student student2 = new Student("Bob", 102, "10th", "B");

int comparisonResult = student1.CompareTo(student2);

if (comparisonResult < 0)
{
    Console.WriteLine($"{student1.Name} comes before {student2.Name}");
}
else if (comparisonResult > 0)
{
    Console.WriteLine($"{student1.Name} comes after {student2.Name}");
}
else
{
    Console.WriteLine($"{student1.Name} is the same as {student2.Name}");
}

Output

Output

Conclusion

The IComparable interface in C# allows you to define a natural ordering for instances of a class. By implementing the IComparable interface, you can provide a consistent way to compare objects of your class, which is useful for sorting and ordering operations.

I hope it was helpful.


Similar Articles