Search code examples
c#icomparablevaluetuple

Why does ValueTuple use non-standard IComparable implementation?


The documentation for ValueTuple.IComparable.CompareTo(Object) says it returns:

0 if other is a ValueTuple instance; otherwise, 1 if other is null.

This makes the IComparable implementation seemingly useless other than perhaps not breaking code that might expect the interface to be implemented. The older reference Tuple class does follow the standard implementation (although it might only work if the items support IComparable).

The documentation says IComparable indicates the type can be sorted, which is not the case with ValueTuple:

This interface is implemented by types whose values can be ordered or sorted. It requires that implementing types define a single method, CompareTo, that indicates whether the position of the current instance in the sort order is before, after, or the same as a second object of the same type. (...)

The implementation of the CompareTo method must return an Int32 that has one of three values, as shown in the following table.

Less than zero The current instance precedes the object specified by the CompareTo method in the sort order.

Zero This current instance occurs in the same position in the sort order as the object specified by the CompareTo method.

Greater than zero This current instance follows the object specified by the CompareTo method in the sort order.

So my questions are:

  • Why doesn't ValueTuple implement CompareTo like Tuple does?
  • And why does it implement IComparable even though it doesn't support meaningful sorting?

Solution

  • The non-generic ValueTuple represents an empty tuple. Since ValueTuple is a struct, that means every ValueTuple instance is equal, and so a collection of nothing but empty ValueTuples doesn't need to be sorted.

    Comparing a ValueTuple to null returns 1 for the same reason comparing an empty string to null returns 1 — because you're comparing something to nothing :)

    The generic variants of ValueTuple that represent tuples of one or more elements all implement IComparable.CompareTo() the way you would expect.

    Note that Tuple itself is a static class, whereas all of its generic variants represent non-empty tuples. Tuple just contains factory methods for its non-empty variants.