IComparableT as an Example of Implementing an Interface

Interfaces can seem abstract until you seem them in practice. The IComparable and IComparable are great examples of why interfaces can be helpful to us.

Let’s say that in a program for a online store, we have a variety of items you can buy. Each item has a name, an ID number, and a price.

publicclassItem{publicstringname;// though public variables are generally bad practice,
publicintidNumber;// to keep this example simple we will use them instead
publicdecimalprice;// of a property.
// body omitted for brevity
}

We have our Items stored inside of a List, 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 already has. However, as our Item class is right now, there is no way for the List to understand what order to sort the list. Here is where the IComparable interface comes in.

To correctly implement the CompareTo method, CompareTo should return a positive number if the parameter is “less than” the current one, zero if they are equal, and a negative number if the parameter is “greater than”.

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 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, 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.