skip to content

In C#, why is `rate == double.NaN` always false for a double rate, yet `List<double>.Contains(double.NaN)` can find a NaN?

level: seniorimportance: should knowfreq 40%

answer

  1. IEEE 754 comparison is unordered
  2. operator versus Equals
  3. what collections compare with
  4. the IsNaN family

basics

~10 s

The == operator follows IEEE 754, where NaN is unequal to everything, itself included. double.Equals(double) treats two NaNs as equal, and List<double>.Contains compares with Equals, so it finds them. Test with double.IsNaN.

solid answer

~40 s

`double` and `float` arithmetic never throws: `0.0 / 0.0` is NaN and `1.0 / 0.0` is positive infinity, so a failed ratio becomes a NaN that flows on. The `==` operator follows IEEE 754, where NaN is unordered, so `rate == double.NaN` is always `false`, `!=` is always `true`, and `<`, `>`, `<=`, `>=` are all `false`. `double.Equals(double)` is different: it returns `true` when both values are NaN, which keeps equality reflexive for collections. `List<T>.Contains`, `Dictionary` keys and `HashSet<T>` use `EqualityComparer<double>.Default`, which calls `Equals`, so they find NaN. `CompareTo` orders NaN below negative infinity, so `Array.Sort` puts it first. Test with `double.IsNaN` or `double.IsFinite`; analyzer CA2242 flags a comparison with `double.NaN`.

code

csharp · 20 lines
csharp
double failed = 0, attempted = 0;
double errorRate = failed / attempted;              // 0.0 / 0.0 is NaN, no exception

Console.WriteLine(errorRate == double.NaN);         // False, whatever errorRate holds
Console.WriteLine(double.IsNaN(errorRate));         // True
Console.WriteLine(errorRate.Equals(double.NaN));    // True: Equals treats NaN as equal to NaN
Console.WriteLine(errorRate > 0.05 || errorRate <= 0.05); // False: every ordered comparison is false

var samples = new List<double> { 0.01, errorRate };
Console.WriteLine(samples.Contains(double.NaN));    // True: List<T>.Contains uses Equals

Console.WriteLine(double.IsPositiveInfinity(1 / attempted)); // True
try
{
    Console.WriteLine(checked((int)errorRate));
}
catch (OverflowException)
{
    Console.WriteLine("OverflowException");         // checked double-to-int cast of NaN
}

go deeper

for a junior

Recall that double division by zero gives infinity or NaN instead of throwing, and that double.IsNaN is the correct test.

for a middle

Explain IEEE 754 unordered comparison for the operators and why Equals and CompareTo deliberately treat NaN as equal to itself.

for a senior

Diagnose a threshold check or a dashboard that went silent because a NaN propagated, and add IsFinite guards at the boundaries.

for a principal

Decide where a codebase allows NaN as a missing-value marker and where it must be rejected, and enforce CA2242 as part of that rule.

## Where NaN and infinity come from In C#, `float` and `double` arithmetic **never throws**. Following IEEE 754, an operation with no finite answer produces a special value: | Expression (double operands) | Result | |---|---| | `1.0 / 0.0` | `double.PositiveInfinity` | | `-1.0 / 0.0` | `double.NegativeInfinity` | | `0.0 / 0.0` | `double.NaN` | | `5.0 % 0.0` | `double.NaN` | | `double.MaxValue * 2` | `double.PositiveInfinity` | The integral types and `decimal` behave differently: dividing them by zero throws `DivideByZeroException`. So an error-rate calculation such as `failed / attempted` throws for `int` operands but silently yields NaN for `double` operands when nothing was attempted, and the NaN then propagates through later arithmetic (`NaN + 1` is NaN, and `Math.Max(1.0, double.NaN)` is NaN too). ## The == operator: IEEE 754 comparison NaN is **unordered**: it is neither less than, equal to nor greater than any value, itself included. The built-in operators follow that rule exactly: - `rate == double.NaN` is `false` whatever `rate` holds. - `rate != double.NaN` is `true` whatever `rate` holds. - `<`, `>`, `<=` and `>=` against NaN are all `false`, so `rate > 0.05 || rate <= 0.05` can be `false`, and an alert threshold check never fires. - `x != x` is `true` only for NaN. Writing it with the same variable on both sides draws warning CS1718, "Comparison made to same variable; did you mean to compare something else?". The compiler itself does not warn about `== double.NaN`; the code-analysis rule **CA2242, "Test for NaN correctly"**, does, and in .NET 10 it is enabled as a suggestion by default. ## Equals and CompareTo: rules for collections `double` also implements `IEquatable<double>` and `IComparable<double>`, and these do **not** follow the operator semantics: 1. `double.Equals(double)` returns `true` when both values are NaN. The runtime source checks `obj == m_value` and then `IsNaN(obj) && IsNaN(m_value)`. 2. `double.CompareTo` treats NaN as equal to NaN and **less than every other value**, including negative infinity. The reason is that collections need an equality that is reflexive and an ordering that is total. A dictionary key that is not equal to itself could never be looked up again; a sort whose comparisons answer "false" for every question about NaN would produce an inconsistent order. So: - `List<double>.Contains(double.NaN)` and `IndexOf` find NaN, because they use `EqualityComparer<double>.Default`, which calls `Equals`. - A `Dictionary<double, T>` or `HashSet<double>` can store and find a NaN key. - `Array.Sort` on a `double[]` places NaN first, before negative infinity. The same value can therefore be "not equal" under `==` and "equal" under `Equals`. That surprises people who assume the operator and the method always agree. ## Infinity is better behaved The infinities are ordinary values for comparison: `double.PositiveInfinity == double.PositiveInfinity` is `true`, and `PositiveInfinity + 1` is still `PositiveInfinity`. They turn into NaN only through undefined operations, such as `PositiveInfinity - PositiveInfinity` or `PositiveInfinity * 0`. A single infinite reading can therefore poison an average or a sum and then, one step later, become a NaN that every comparison silently ignores. ## Testing correctly - `double.IsNaN(x)` for NaN; `double.IsInfinity`, `double.IsPositiveInfinity` and `double.IsNegativeInfinity` for the infinities. - `double.IsFinite(x)` to accept only real numbers, the right guard before converting, storing or comparing. - Guard the division instead of the result where you can: `attempted == 0 ? 0 : failed / attempted`, if zero is the agreed meaning. ## Converting NaN and infinity - An explicit cast to an integral type, `(int)rate`, gives an **unspecified** value in an unchecked context when `rate` is NaN, infinite or out of range, according to the C# language reference; do not rely on any particular result. - In a checked context the same cast throws `OverflowException`. - Converting NaN or infinity to `decimal` always throws `OverflowException`. ## Putting it together A telemetry aggregator that computes per-minute error rates as `double` should guard the zero-request minute, test incoming values with `double.IsFinite`, and use `double.IsNaN` rather than `== double.NaN` wherever a missing value is meaningful. Code that relies on collections, sorting or `Equals` must expect NaN to compare equal to itself there, even though `==` says otherwise.

  • What does casting a NaN double to int give in C#?
    In an unchecked context the C# language reference calls the result an unspecified value of the destination type, so no code should depend on it. In a checked context, `checked((int)rate)` throws `OverflowException`. The robust pattern is to test `double.IsFinite(rate)` and the range before the cast, and decide explicitly what a missing value means.
  • Why does Array.Sort put NaN first in a C# double array?
    `Array.Sort` uses `double.CompareTo`, which defines a total order where NaN equals NaN and is less than every other value, negative infinity included. The `<` operator cannot be used for sorting because every comparison with NaN is false, which would make the order inconsistent. The same `CompareTo` order applies to `List<double>.Sort`.
  • Does the C# compiler warn about `if (rate == double.NaN)`?
    No; the compiler accepts it silently. The code-analysis rule CA2242, "Test for NaN correctly", flags comparisons with `double.NaN` or `float.NaN`, and in .NET 10 it is enabled as a suggestion by default. The compiler's own CS1718 appears only when the same variable is on both sides, as in `x != x`.

  • rate == double.NaN is the way to detect a NaN result.
  • Dividing a double by zero throws DivideByZeroException.
  • Equals and == always agree for double values.
  • A Dictionary<double, T> can never find a NaN key.
  • Casting NaN to int reliably gives zero in every context.