S2688 — "NaN" should not be used in comparisons

Language
C#
Type
Bug
Severity
Major

Why is this an issue?

double.NaN and float.NaN are not equal to anything, not even themselves.

When anything is compared with NaN using one of the comparison operators >, >=, <, or the equality operator ==, the result will always be false. In contrast, when anything is compared with NaN using the inequality operator !=, the result will always be true.

Instead, the best way to see whether a variable is equal to NaN is to use the float.IsNaN and double.IsNaN methods, which work as expected.

How to fix it

Code examples

Noncompliant code example


var a = double.NaN;

if (a == double.NaN) // Noncompliant: always false
{
  Console.WriteLine("a is not a number");
}
if (a != double.NaN)  // Noncompliant: always true
{
  Console.WriteLine("a is not NaN");
}

Compliant solution


var a = double.NaN;

if (double.IsNaN(a))
{
  Console.WriteLine("a is not a number");
}
if (!double.IsNaN(a))
{
  Console.WriteLine("a is not NaN");
}

↑ Back to top