double.IsNaN()
to check if a double
is NaN
CS-W1003NaN
always evaluates to false
19 var pi = 3.14;
20 // CS-W1003: Invalid comparison against `NaN`.
21 // https://deepsource.io/directory/analyzers/csharp/issues/CS-W1003
22 var isNaN = pi == double.NaN;23
24 // CS-W1025: Potential memory leak inside `for` loop due to `stackalloc`.
25 // https://deepsource.io/directory/analyzers/csharp/issues/CS-W1025.
By specification, NaN
is not equal to anything, not even itself. Therefore, comparing any double
with NaN
will always evaluate to false
. The preferred and right approach is to directly use the double's .isNaN
method.
var d = double.NaN;
d == Double.NaN; // evaluates to false
var d = double.NaN;
double.IsNaN(d); // evaluates to true