CA2242: Test for NaN correctly

 

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

TypeNameTestForNaNCorrectly
CheckIdCA2242
CategoryMicrosoft.Usage
Breaking ChangeNon Breaking

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

Double.NaN, which represents not-a-number, results when an arithmetic operation is undefined. Any expression that tests equality between a value and Double.NaN always returns false. Any expression that tests inequality between a value and Double.NaN always returns true.

To fix a violation of this rule and accurately determine whether a value represents Double.NaN, use M:System.Single.IsNan(System.Single) or M:System.Double.IsNan(System.Double) to test the value.

Do not suppress a warning from this rule.

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

Show: