IComparable<T> as an Example of Implementing an Interface

suggest change

Interfaces can seem abstract until you see them in practice. IComparable and IComparable<T> show why an interface is useful.

In a program for an online store, each item has a name, an ID number, and a price.

public class Item {
    
    public string name; // though public variables are generally bad practice,
    public int idNumber; // to keep this example simple we will use them instead
    public decimal price; // of a property.

    // body omitted for brevity        

}

We have our Items stored inside of a List<Item>, and in our program somewhere, we want to sort our list by ID number from smallest to largest. Instead of writing our own sorting algorithm, we can instead use the Sort() method that List<T> already has. However, as our Item class is right now, there is no way for the List<T> to understand what order to sort the list. Here is where the IComparable interface comes in.

CompareTo returns a positive number when the argument is less than this item, zero when they are equal, and a negative number when the argument is greater. Sort uses only that sign. Subtracting the IDs can overflow when the values are far apart; idNumber.CompareTo(otherItem.idNumber) orders them the same way without that overflow. The calls below print the raw difference.

Item apple = new Item();
apple.idNumber = 15;
Item banana = new Item();
banana.idNumber = 4;
Item cow = new Item();
cow.idNumber = 15;
Item diamond = new Item();
diamond.idNumber = 18;

Console.WriteLine(apple.CompareTo(banana)); // 11
Console.WriteLine(apple.CompareTo(cow)); // 0
Console.WriteLine(apple.CompareTo(diamond)); // -3

Here’s the example Item’s implementation of the interface:

public class Item : IComparable<Item> {
    
    private string name;
    private int idNumber;
    private decimal price;

    public int CompareTo(Item otherItem) {

        return (this.idNumber - otherItem.idNumber);

    }

    // rest of code omitted for brevity    

}

On a surface level, the CompareTo method in our item simply returns the difference in their ID numbers, but what does the above do in practice?

Now, when we call Sort() on a List<Item> object, the List will automatically call the Item’s CompareTo method when it needs to determine what order to put objects in. Furthermore, besides List<T>, any other objects that need the ability to compare two objects will work with the Item because we have defined the ability for two different Items to be compared with one another.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents