[This is my response shameless ripped from the other post. It would be nice is someone explored this further -- double.CompareTo
and double.CompareTo(double)
are well-defined, as indicated below so I suspect there is some Array.Sort
magic happening for the specific type.]
Array.Sort(double[])
: doesn't seem to be using CompareTo(double[])
as expected and this may very well be a bug -- note the difference in Array.Sort(object[]) and Array.Sort(double[]) below. I would love clarification/corrections on the following.
First, the double.CompareTo(T)
method documentation -- this ordering is well-defined according to the documentation:
Less than zero:
This instance is less than value.
-or-
This instance is not a number (NaN) and value is a number.
Zero:
This instance is equal to value.
-or-
Both this instance and value are not a number (NaN), PositiveInfinity, or NegativeInfinity.
Greater than zero:
This instance is greater than value.
-or-
This instance is a number and value is not a number (NaN).
In LINQPad (3.5 and 4, both have same results):
0d.CompareTo(0d).Dump();
double.NaN.CompareTo(0d).Dump();
double.NaN.CompareTo(double.NaN).Dump();
0d.CompareTo(double.NaN).Dump();
Using CompareTo(object)
has the same results:
0d.CompareTo((object)0d).Dump();
double.NaN.CompareTo((object)0d).Dump();
double.NaN.CompareTo((object)double.NaN).Dump();
0d.CompareTo((object)double.NaN).Dump();
So that's not the problem.
Now, from the Array.Sort(object[])
documentation -- there is no use of >
, <
or ==
(according to the documentation) -- just CompareTo(object)
.
Sorts the elements in an entire one-dimensional Array using the IComparable
implementation of each element of the Array.
Likewise, Array.Sort(T[])
uses CompareTo(T)
.
Sorts the elements in an entire Array using the IComparable(Of T) generic interface implementation of each element of the Array.
Let's see:
LINQPad (4):
var ar = new double[] {double.NaN, 0, 1, double.NaN};
Array.Sort(ar);
ar.Dump();
LINQPad (3.5):
var ar = new double[] {double.NaN, 0, 1, double.NaN};
Array.Sort(ar);
ar.Dump();
LINQPad (3.5) -- NOTE THE ARRAY IS OF OBJECT and the behavior is "expected" per the CompareTo
contract.
var ar = new object[] {double.NaN, 0d, 1d, double.NaN};
Array.Sort(ar);
ar.Dump();
Hmm. Really. In conclusion:
I HAVE NO IDEA -- but I suspect there is some "optimization" resulting in CompareTo(double)
not being invoked.
Happy coding.
double.CompareTo
is correct in .net 3.5. – CodesInChaos