A long overdue refactoring for CompareTo

We've all used the CompareTo method to sort elements or to compare strings for some reason. It's also possible that you've implemented your own CompareTo by implementing the IComparable interface (or its generic version IComparable<T>).

There's one thing that always bugs me when using or implementing that method.

Why does it return an int and what do the return values mean?

I rarely use the method, but when I do I always have to look-up the documentation to know that:

  • Less than zero means this instance is less than the given object
  • Zero means they are equal (this one I remember obviously)
  • Greater than zero means this instance is greater than the give object

It seems simple enough, but I'm never a 100% certain what the positive or negative values really mean (although they do make some sense).

It's not that hard to remember or to look-up, but why do I need to do extra work to understand the method when the solution is so simple? I'm sure I'm not the only one who keeps forgetting that information.

The solution

A simple solution that should have been done a long time ago would be to simply use enums for return values.

public enum ComparisonResults: int
    IsLessThanOther = -1,
AreEqual = 0,

IsGreaterThanOther = 1


And the implementation of the method would look something like this:

public ComparisonResults CompareTo(T other)

There we go, that wasn't so hard and now no one ever has to go check that documentation again.

Note that I haven't really thought of the exact names to use in the results, but you get the point (hopefully).

Update: There's an interesting discussion over at reddit about this post that you might want to read.

Michel Billard's profile picture

A web developer's musings on software, product management, and other vaguely related topics.