Reputation: 3450
Why does the following code snippet returns 1:
double i = double.NaN;
double? i2 = null;
i.CompareTo(i2);
From my point of view it makes no sense. An Exception would be more appropriate.
What do you think was the reasoning behind the decision.
Upvotes: 7
Views: 775
Reputation: 23626
When you decompile CompareTo
of double
, you can see:
public int CompareTo(object value)
{
if (value == null)
return 1;
just to put null elements at the bottom of any sorted sequence.
Upvotes: 2
Reputation: 14618
From the documentation on CompareTo:
The value parameter must be null or an instance of Double; otherwise, an exception is thrown. Any instance of Double, regardless of its value, is considered greater than null.
The value parameter in your example is null
. NaN
is therefore considered greater than null which is why CompareTo
correctly returns 1
.
Upvotes: 3
Reputation: 101680
From the MSDN documentation on IComparable.CompareTo()
:
By definition, any object compares greater than (or follows) null, and two null references compare equal to each other.
This is also apparent from the Double.CompareTo(object)
documentation:
Returns a positive integer if This instance is greater than value. -or- This instance is a number and value is not a number (NaN). -or- value is a null reference (Nothing in Visual Basic).
As Adam Houldsworth points out, if something.CompareTo(somethingElse)
threw an exception when somethingElse is null, then sorting and things like that would require lots of extra exception handling.
Upvotes: 2