A C# survey report counts responses with `Age >= 18` and with `Age < 18` on an `int? Age`; why don't the two counts add up to the total?
answer
- a third state, not two
- comparisons with null are false
- negation is not the complement
- sorting disagrees with <
basics
~20 sLifted ordering comparisons on int? return false whenever an operand is null, so a response with no age is neither >= 18 nor < 18 and drops out of both counts; !(Age < 18) adds them back.
solid answer
~50 s`<`, `>`, `<=` and `>=` on `int?` are lifted to return a plain `bool`, and that bool is `false` whenever either side is null. For a skipped age, `Age >= 18` and `Age < 18` are both `false`, so those responses vanish from both buckets; `!(Age < 18)` is `true` for them, so rewriting one test as the negation of the other quietly moves them into the adult bucket. Even `null <= null` is `false`, although `null == null` is `true`. Sorting follows a different rule: `Nullable.Compare` and the default comparer treat null as smaller than every value, so an ordered list puts nulls first while `null < 16` is `false`. The fix is to make the third state explicit, for example a switch expression with a `null` arm, or a separate count of unknown ages.
code
csharp · 28 linesusing System;
using System.Linq;
int?[] ages = { 34, null, 16, null, 71 };
int adults = ages.Count(a => a >= 18);
int minors = ages.Count(a => a < 18);
int notMinors = ages.Count(a => !(a < 18));
Console.WriteLine($"{adults} + {minors} of {ages.Length}"); // 2 + 1 of 5
Console.WriteLine(notMinors); // 4
int? first = null, second = null;
Console.WriteLine(first <= second); // False
Console.WriteLine(first == second); // True
Console.WriteLine(Nullable.Compare(first, 16)); // -1
foreach (var age in ages)
{
string band = age switch
{
null => "unknown",
< 18 => "minor",
_ => "adult"
};
Console.Write(band + " "); // adult unknown minor unknown adult
}
Console.WriteLine();go deeper
Recall that comparing an empty int? with < or >= gives false, so a null fails every ordering test.
Explain how the ordering operators are lifted to a plain bool, why <= on two nulls is false, and why the default comparer still ranks null first.
Diagnose missing rows in a report by counting nulls, catch negated nullable comparisons in review, and give the unknown state an explicit branch.
Require reports over optional data to show the unknown count beside the buckets, so a refactoring that moves unknowns between buckets is visible in the numbers.
## The symptom A survey form stores `int? Age`; respondents may skip it. The statistics job counts adults with `Age >= 18`, minors with `Age < 18`, and reports both beside the total. With ages `34, null, 16, null, 71`, it reports **2 adults + 1 minor of 5 responses**. Nothing threw, no warning appeared, and two responses are simply missing. A colleague "simplifies" the adult filter to `!(Age < 18)` and the adult count jumps to 4. ## The rule: lifted ordering comparisons return `false` The ordering operators on a nullable value type are lifted to return a plain `bool`, not `bool?`. The C# reference states the rule directly: for `<`, `>`, `<=` and `>=`, if one or both operands are null, the result is `false`. | Expression, `Age` empty | Result | |---|---| | `Age >= 18` | `false` | | `Age < 18` | `false` | | `!(Age < 18)` | `true` | | `Age <= otherEmptyAge` | `false` | | `Age == otherEmptyAge` | `true` | The last two rows are the surprise inside the surprise: two empty values are equal under `==` but not less-than-or-equal under `<=`. ## Why negation is not the complement With a plain `int`, every value satisfies exactly one of `x < 18` and `x >= 18`, so `!(x < 18)` and `x >= 18` are interchangeable. A nullable value has **three** states, and the lifted comparisons map the third one to `false` in both directions: - `Age >= 18` excludes unknown ages. - `Age < 18` excludes unknown ages. - `!(Age < 18)` includes unknown ages. - `!(Age >= 18)` includes unknown ages too, so a "not adult" count would swallow them instead. Any refactoring that turns a comparison into the negation of its opposite, or inverts an `if` and swaps the branches, changes which bucket the unknowns land in. Code review rarely catches it because the code reads as equivalent. ## Sorting uses a different rule Ordering a sequence does not use the lifted operators. `Nullable.Compare<T>` returns -1 when the first argument is empty and the second is not, and the default comparer for `int?` follows the same rule, so sorting the ages puts the nulls **first**. The comparison `null < 16` is `false`, yet a sorted list ranks null below 16. A paging or bucketing scheme that mixes sorted positions with `<` tests can disagree with itself. The LINQ aggregates over `int?` add a third behaviour: `Sum`, `Average`, `Min` and `Max` skip the nulls, which is usually right for a mean but hides how many answers were missing. ## Why the compiler produces `false` Roslyn lowers a lifted `<` on temporaries `x` and `y` to `(x.GetValueOrDefault() < y.GetValueOrDefault()) & (x.HasValue & y.HasValue)`. The payload comparison runs on zero-initialised fields, and the flag test then forces the result to `false` whenever either side is empty. The equality operator is lowered differently, comparing the flags with `==` instead of `&`, which is why `==` treats two empty values as equal and `<=` does not. ## Where it hides in real code - **Guard clauses**: `if (response.Age < 18) return;` lets every unknown age through to the code below the guard. - **Inverted conditions**: an `if (Age >= 18) { ... } else { ... }` puts unknowns in the `else` branch; swapping the test to `Age < 18` moves them to the other branch. - **Filters**: a query that keeps `r.Age >= 18` and a second that keeps `r.Age < 18` both drop unknowns, so per-bucket totals never reconcile with the response count. - **Date ranges**: `r.LastLogin < cutoff` is `false` for a respondent who never logged in, so an "inactive users" filter written that way misses exactly the most inactive ones. ## Fixes 1. **Make the third state a branch**: a switch expression with a `null` arm, `age switch { null => "unknown", < 18 => "minor", _ => "adult" }`, forces a decision for every state. 2. **Report the unknowns**: count `Age is null` separately, so adults + minors + unknown equals the total and the report can be checked. 3. **Never negate a nullable comparison to get its opposite**: write the positive test you mean (`Age >= 18`) and handle null on its own line. 4. **Substitute only on purpose**: `(Age ?? 0) < 18` puts every unknown among the minors; that may be a policy, but it should be written as one. A relational pattern such as `Age is >= 18` behaves like the lifted comparison here, matching only a non-null value that satisfies the test, so it does not remove the need for an explicit null branch.
- Why does `null <= null` return false when `null == null` returns true?They follow different lifting rules. `==` and `!=` are lifted so that two nulls are equal, while `<`, `>`, `<=` and `>=` return `false` whenever an operand is null, with no special case for both. So `<=` is not the same as `<` or `==` for nullable operands.
- If `null < 16` is false, why does sorting the ages put the nulls first?Sorting does not call the lifted `<`. It uses `Nullable.Compare<T>` or the default comparer for `int?`, which rank an empty value below any value and two empty values as equal. The two rules disagree by design, so do not mix sorted positions with `<` tests on the same data.
- null < 18 is true because null counts as zero
- !(Age < 18) and Age >= 18 mean the same for int?
- Comparing a null int? with < throws InvalidOperationException
- null <= null is true because null == null is true
- Sorting int? values puts nulls last