Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the sort order of System.ValueTuple officially specified, and where?

The new ValueTuple types in C# 7 implement IComparable, but the only documentation I have been able to find on their implementation of this simply states that CompareTo's return value indicates relative position "in the sort order". It does not state what the "sort order" referred to actually is.

By examining the source, I can find that the order is what I would expect - it delegates to comparing the first field by its default Comparer, then using the other fields one at a time, in order, to break ties. I would prefer not to depend on this without a guarantee that it's not considered an implementation detail that could change without violating specification, however.

Is this behavior actually documented anywhere?

like image 256
Douglas Avatar asked Oct 18 '17 05:10

Douglas


1 Answers

According to the source code, CompareTo calls the Compare methods of the default comparers

    public int CompareTo(ValueTuple<T1, T2, T3> other)
    {
        int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
        if (c != 0) return c;

        c = Comparer<T2>.Default.Compare(Item2, other.Item2);
        if (c != 0) return c;

        return Comparer<T3>.Default.Compare(Item3, other.Item3);
    }

but you can explicitly provide a customer comparer

int IStructuralComparable.CompareTo(object other, IComparer comparer)
like image 64
devio Avatar answered Oct 13 '22 23:10

devio