This documentation is archived and is not being maintained.

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.







Breaking Change


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.

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