CA2242: Test for NaN correctly
Note
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here
Item | Value |
---|---|
TypeName | TestForNaNCorrectly |
CheckId | CA2242 |
Category | Microsoft.Usage |
Breaking Change | Non Breaking |
Cause
An expression tests a value against System.Single.NaN or System.Double.NaN.
Rule Description
System.Double.NaN, which represents not-a-number, results when an arithmetic operation is undefined. Any expression that tests equality between a value and System.Double.NaN always returns false
. Any expression that tests inequality 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.
using System;
namespace UsageLibrary
{
class NaNTests
{
static double zero;
static void Main()
{
Console.WriteLine( 0/zero == double.NaN );
Console.WriteLine( 0/zero != double.NaN );
Console.WriteLine( double.IsNaN(0/zero) );
}
}
}
Imports System
Namespace UsageLibrary
Class NaNTests
Shared zero As Double
Shared Sub Main()
Console.WriteLine( 0/zero = Double.NaN )
Console.WriteLine( 0/zero <> Double.NaN )
Console.WriteLine( Double.IsNaN(0/zero) )
End Sub
End Class
End Namespace