CA2242: Test for NaN correctly
Property | Value |
---|---|
Rule ID | CA2242 |
Title | Test for NaN correctly |
Category | Usage |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 9 | As suggestion |
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 Namespace
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));
}
}