Why does ValueTuple use a custom implementation of IComparable?

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

0 if the other is an instance of ValueTuple; otherwise 1 if the other is null.

This makes the IComparable implementation seemingly useless, except perhaps not breaking the code, which can expect the interface to be implemented. The older Tuple reference class implements the standard implementation (although it can only work if the elements support IComparable ).

The documentation states that IComparable indicates that 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. This requires that the implementation types define one method, CompareTo, which indicates whether the position of the current instance is sorted before, after, or similarly to a second object of the same type. (...)

The implementation of the CompareTo method should return Int32, which has one of three values, as shown in the following table.

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

Zero This current instance appears at the same position in the sort as the object specified by the CompareTo Method.

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

So my questions are:

  • Why ValueTuple n't ValueTuple implement CompareTo like Tuple?
  • And why does it implement IComparable , although it does not support meaningful sorting?
+5
source share
1 answer

An undefined ValueTuple is an empty tuple. Since ValueTuple is a structure, this means that every instance of ValueTuple is equal, and therefore the collection does not need to be sorted except for an empty ValueTuples.

Comparing ValueTuple with null returns 1 for the same reason, comparing an empty string with null returns 1 - because you are not comparing anything :)

Common ValueTuple variants that represent tuples of one or more elements implement IComparable.CompareTo() as you would expect.

Note that Tuple itself is a static class, while all its common variants are non-empty tuples. Tuple simply contains factory methods for its non-empty options.

+4
source

Source: https://habr.com/ru/post/1275333/


All Articles