skip to content

A C# loan rule rejects when `creditScore is < 600`, with creditScore an `int?`; why does a null score get through, and how do you fix it?

level: seniorimportance: should knowfreq 35%

answer

  1. what a relational pattern does with null
  2. NaN compares false both ways
  3. not turns a non-match into a match
  4. the constant's type is a type test

basics

~20 s

A relational pattern never matches null, so creditScore is < 600 is false for an empty int? and the reject branch is skipped. Write is null or < 600, or the equivalent is not >= 600, which does match null.

solid answer

~50 s

A relational pattern never matches null: the language reference says it does not match when the value is null or cannot be converted to the constant's type, so `creditScore is < 600` and `creditScore is >= 600` are both `false` for an empty `int?`. A rule written as "reject when below 600" therefore lets a missing score through. State what null means: `creditScore is null or < 600` rejects it, and so does `creditScore is not >= 600`, because `not` turns the failed match into a match. `double.NaN` behaves the same way, since every ordered comparison with NaN is false: `ratio is > 0.45` lets a NaN ratio through while `ratio is not <= 0.45` catches it. And a boxed `long` never matches `> 3`, because the `int` constant makes the pattern a type test for `int`.

code

csharp · 13 lines
csharp
int? creditScore = null;           // bureau returned nothing
double debtToIncome = double.NaN;  // 0 / 0 from an empty income history

Console.WriteLine(creditScore is < 600);            // False: the reject rule never fires
Console.WriteLine(creditScore is not >= 600);       // True: null is rejected
Console.WriteLine(creditScore is null or < 600);    // True: the same rule, spelled out

Console.WriteLine(debtToIncome is > 0.45);          // False: NaN slips past
Console.WriteLine(debtToIncome is not <= 0.45);     // True: NaN is rejected

object boxed = 5L;                                  // a long, boxed
Console.WriteLine(boxed is > 3);                    // False: the constant 3 is an int
Console.WriteLine(boxed is > 3L);                   // True

go deeper

for a junior

Remember that a relational pattern such as < 600 is false for null, so a check against a nullable value must say what null means.

for a middle

Explain why a relational pattern never matches null, why NaN fails in both directions, why not then matches both, and how an object input becomes a type test.

for a senior

Audit reject rules for null, NaN and boxed values slipping through, prefer explicit is null or forms, and test every boundary.

for a principal

Make missing-data handling an explicit, reviewed decision in rule code, so each field states whether absence rejects, accepts or escalates.

## A relational pattern is a type test plus a comparison A **relational pattern** such as `< 600` compares its input with a constant using `<`, `<=`, `>` or `>=`. The language reference states the rule for awkward inputs in one line: if the value is null, or fails to convert to the constant's type through a **nullable or unboxing conversion**, the relational pattern does not match. Only otherwise is the comparison evaluated. The C# 9 design adds that, for an input that is not already a comparable type, the constant's type acts as an implicit type test. Three inputs fall through that gap in rule code: - an empty `Nullable<T>`, such as a credit score the bureau did not return; - a floating-point NaN, such as a ratio computed as `0.0 / 0.0`; - a boxed value of a different type, such as a `long` stored in an `object`. ## Null: neither below nor above For `int? creditScore = null`, every relational pattern fails, in both directions: | Test | Result for null | Result for 550 | Result for 700 | |---|---|---|---| | `creditScore is < 600` | false | true | false | | `creditScore is >= 600` | false | false | true | | `creditScore is not >= 600` | true | true | false | | `creditScore is null or < 600` | true | true | false | A reject rule written as `if (creditScore is < 600) return Reject;` therefore skips null and approves an applicant with no score. In a switch expression the effect is the same: an arm `< 600 => Decision.Reject` does not match null, so a later catch-all arm such as `_ => Decision.Approve` handles it. Nothing throws; the pattern just reports "no match". The same holds for the lifted comparison `creditScore < 600`, which is also false when the operand is null; the pattern form does not make null safer, only more visible once you know the rule. ## NaN: same shape, different reason A `double` NaN converts fine, but every ordered comparison with NaN is false, so `ratio is > 0.45` and `ratio is <= 0.45` are both false. A debt-to-income check that rejects `> 0.45` lets a NaN ratio through. Two related rules: - `ratio is < double.NaN` is rejected outright with CS8782, "Relational patterns may not be used for a floating-point NaN." - A **constant pattern** may use NaN: `ratio is double.NaN` is true for NaN, which `ratio == double.NaN` never is. ## not turns a non-match into a match `not` succeeds whenever its operand fails, whatever the reason. That makes it the compact fix for a reject rule, and the reason to read every `not` carefully: 1. Reject null and low scores: `creditScore is not >= 600`, or the explicit `creditScore is null or < 600`. 2. Reject NaN and high ratios: `ratio is not <= 0.45`, or `double.IsNaN(ratio) || ratio > 0.45`. 3. Accept only known good scores: `creditScore is >= 600`, which already excludes null. The explicit forms cost a few characters and tell the next reader that missing data was considered. `is not >= 600` is equivalent but easy to "simplify" back into `is < 600` in a refactor. ## Boxed values and the constant's type When the input is typed `object`, the constant's type decides the type test: ```csharp object boxed = 5L; bool a = boxed is > 3; // false: 3 is an int, the box holds a long bool b = boxed is > 3L; // true bool c = boxed is long n and > 3; // true: test the type first, then compare ``` The comparison never converts a `long` into an `int`; the unboxing conversion to `int` simply fails and the pattern does not match. Rule engines that keep values in `object` or a dictionary of `object` hit this when a value's runtime type differs from the literal in the rule. ## Writing the rule so missing data is a decision - Decide per field whether missing means reject, accept or ask, and write that case explicitly with `null` or `double.NaN`. - Prefer accept rules (`is >= 600`) over reject rules when a missing value should never pass. - Test the boundaries: null, NaN, the limit itself, and one value each side of it.

  • Can a pattern test for NaN directly?
    Yes, with a constant pattern: `ratio is double.NaN` is true for NaN, which `ratio == double.NaN` never is. A relational pattern with a NaN constant, such as `ratio is < double.NaN`, is rejected with CS8782, "Relational patterns may not be used for a floating-point NaN."
  • Is creditScore is < 600 any different from creditScore < 600 when the score is null?
    No: the lifted `<` on `int?` is also false when an operand is null. Negation is where forms diverge: `creditScore is not >= 600` and `!(creditScore >= 600)` are true for null, while `creditScore is < 600` is false. Write the null case explicitly so a refactor cannot flip it.
  • Why is boxed is > 3 false when object boxed = 5L;?
    When the input is `object`, the relational pattern first tests for the constant's type. The constant `3` is an `int`, so a boxed `long` fails the unboxing test and no comparison happens. Write `> 3L`, or test the type first: `boxed is long n and > 3`.

  • A null int? counts as less than any number in a relational pattern.
  • x is not < 600 and x is >= 600 always give the same answer.
  • NaN compares greater than every number, so is > 0.45 catches it.
  • object o = 5L; o is > 3 converts the long to int and compares it.
  • A relational pattern throws InvalidOperationException on an empty Nullable<T>.