Export (0) Print
Expand All
Expand Minimize

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

An expression tests a value against System.Single.Nan or System.Double.Nan.

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.

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.

Do not exclude a warning from this rule.

The following example shows two expressions that incorrectly test a value against NaN and an expression that correctly uses 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) );
      }
   }
}

Community Additions

ADD
Show:
© 2015 Microsoft