All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S2688.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

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");
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy