Cause
An expression tests a value against System.Single.NaN or System.Double.NaN.
Rule description
System.Double.NaN, which represents a value that's not a number, results when an arithmetic operation is undefined. Any expression that tests for equality between a value and System.Double.NaN always returns false. Any expression that tests for inequality (!= in C#) between a value and System.Double.NaN always returns true.
How to fix violations
To fix a violation of this rule and accurately determine whether a value represents System.Double.NaN, use System.Single.IsNaN or System.Double.IsNaN to test the value.
When to suppress warnings
Do not suppress a warning from this rule.
Example
The following example shows two expressions that incorrectly test a value against System.Double.NaN and an expression that correctly uses System.Double.IsNaN to test the value.
Imports System
Namespace ca2242
Class NaNTests
Shared zero As Double
Shared Sub Main2242()
Console.WriteLine(0 / zero = Double.NaN)
Console.WriteLine(0 / zero <> Double.NaN)
Console.WriteLine(Double.IsNaN(0 / zero))
End Sub
End Class
End Namespacesample · csharpdocs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2242.cssnippet1
using System;
namespace ca2242
{
//<snippet1>
class NaNTests
{
static double zero = 0;
static void RunIt()
{
Console.WriteLine(0 / zero == double.NaN);
Console.WriteLine(0 / zero != double.NaN);
Console.WriteLine(double.IsNaN(0 / zero));
}
}
//</snippet1>
}