Test for NaN correctly
This warning is supported in the stand-alone version of FxCop only. It is not supported in Code Analysis, which is integrated into Visual Studio.
TypeName |
TestForNaNCorrectly |
CheckId |
CA2242 |
Category |
Microsoft.Usage |
Breaking Change |
NonBreaking |
Cause
An expression tests a value against System.Single.Nan or System.Double.Nan.
Rule Description
NaN, which represents not-a-number, results when an arithmetic operation is undefined, such as any number divided by zero. Any expression that tests equality between a value and NaN always returns false. Any expression that tests inequality between a value and NaN always returns true. Therefore, any attempt to test for NaN will always return the same value, regardless of the value of the number being compared to NaN. NaN is not meant to be used in a conditional expression.
How to Fix Violations
To fix a violation of this rule and accurately determine whether a value represents NaN, use System.Single.IsNan(System.Single) or System.Double.IsNan(System.Double) to test the value.
When to Exclude Warnings
Do not exclude a warning from this rule.
Example
The following example shows two expressions that incorrectly test a value against NaN and an expression that correctly uses IsNaN to test the value.
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
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) );
}
}
}