C#idiomatic C#
ca2242fundamentals/code-analysis/quality-rules

Code analysis

CA2242: Test for NaN correctly

Learn about code analysis rule CA2242: Test for NaN correctly

CA2242 Usage enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

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

Rule description

System.Double.NaN, which represents a value that's not a number, results when an arithmetic operation is undefined. Any expression that tests for equality between a value and System.Double.NaN always returns false. Any expression that tests for inequality (!= in C#) between a value and System.Double.NaN always returns true.

How to fix violations

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

When to suppress warnings

Do not suppress a warning from this rule.

Example

The following example shows two expressions that incorrectly test a value against System.Double.NaN and an expression that correctly uses System.Double.IsNaN to test the value.

sample · vbdocs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/ca2242-test-for-nan-correctly_1.vb

vb
Imports System

Namespace ca2242

    Class NaNTests

        Shared zero As Double

        Shared Sub Main2242()
            Console.WriteLine(0 / zero = Double.NaN)
            Console.WriteLine(0 / zero <> Double.NaN)
            Console.WriteLine(Double.IsNaN(0 / zero))
        End Sub

    End Class

End Namespace

sample · csharpdocs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2242.cssnippet1

csharp
using System;

namespace ca2242
{
    //<snippet1>
    class NaNTests
    {
        static double zero = 0;

        static void RunIt()
        {
            Console.WriteLine(0 / zero == double.NaN);
            Console.WriteLine(0 / zero != double.NaN);
            Console.WriteLine(double.IsNaN(0 / zero));
        }
    }
    //</snippet1>
}