Comparing NaN and null returns illogical value

Why the following code fragment returns 1:

double i = double.NaN; double? i2 = null; i.CompareTo(i2); 

From my point of view this does not make sense. An exception would be more appropriate.

What do you think is the reason for making the decision.

+7
source share
3 answers

From the documentation for CompareTo :

Value must be null or an instance of Double; otherwise, an exception is thrown. Any Double instance, regardless of its value, is considered to be greater than zero.

The value parameter in your example is null . NaN therefore considered greater than zero, therefore CompareTo correctly returns 1 .

+4
source

In the MSDN documentation on IComparable.CompareTo() :

By definition, any object is compared more (or follows) null, and two null references are compared with each other.

This can also be seen from the Double.CompareTo(object) documentation:

Returns a positive integer if this instance is greater than the value. -or- This instance is a number and a value, not a number (NaN). -or-value is a null reference (Nothing in Visual Basic).

As Adam Haldsworth points out, if something.CompareTo(somethingElse) throws an exception when somethingElse is null, then sorting and similar things will require a lot of extra exception handling.

+2
source

When you decompile CompareTo from double , you can see:

 public int CompareTo(object value) { if (value == null) return 1; 

just to place zero elements at the bottom of any sorted sequence.

+2
source

All Articles