Value compared against Double.NaN or Single.NaN

ID

vbnet.correctness.comparison_nan

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Numeric

Language

VB.NET

Description

Reports a value compared for equality or inequality against the Double.NaN or Single.NaN constant with the = or <> operator, instead of the Double.IsNaN / Single.IsNaN predicate.

Rationale

NaN ("not a number") is defined to be unordered, so it compares unequal to every value including itself. value = Double.NaN is therefore always False - even when value really is NaN - and value <> Double.NaN is always True. The comparison looks like a guard but never guards anything: the NaN slips past the check and propagates through the arithmetic that follows, until it surfaces as a nonsensical total, a chart with a missing point, or a NaN written to a database column.

The following code illustrates the pattern detected by this rule:

Public Function IsUnavailable(ByVal reading As Double) As Boolean
    ' FLAGGED: Value compared against Double.NaN or Single.NaN
    Return reading = Double.NaN
End Function

Remediation

Test for NaN with the shared predicate Double.IsNaN (or Single.IsNaN), which inspects the bit pattern rather than comparing values. Negate it for the "has a real value" case.

' Before: always False, so the guard never fires
If reading = Double.NaN Then
    Return
End If

' After
If Double.IsNaN(reading) Then
    Return
End If

Configuration

This detector does not need any configuration.