Export (0) Print
Expand All
Expand Minimize

CA2242: Test for NaN correctly







Breaking Change

Non Breaking

An expression tests a value against Single.Nan or 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 Single.IsNan or Double.IsNan 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.

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
© 2015 Microsoft