skip to content

In C#, what does `applicant is { Age: >= 18, MonthlyIncome: >= 2500m }` test, including when applicant is null?

level: juniorimportance: must knowfreq 62%

answer

  1. braces name the members to test
  2. each member gets its own pattern
  3. a constant on the right of >=
  4. what braces imply about null

basics

~20 s

It is a property pattern with relational subpatterns: it is true only when applicant is non-null, Age is at least 18 and MonthlyIncome is at least 2500. A null applicant fails the match without throwing.

solid answer

~40 s

That is a **property pattern** (C# 8) whose subpatterns are **relational patterns** (C# 9). The braces first require a non-null input, then read each named property or field and match its value against the nested pattern; every subpattern must match. A null `applicant` therefore gives `false`, not a `NullReferenceException`. It replaces `if (a != null) { if (a.Age >= 18) { if (a.MonthlyIncome >= 2500m) ... } }` with one expression, and `and` builds a range on one member, as in `Age: >= 18 and < 70`. The value on the right of `>=` must be a compile-time constant: a local variable or a `static readonly` field fails with CS9135.

code

csharp · 26 lines
csharp
Applicant? missing = null;
var ana = new Applicant(34, 4200m);
var teen = new Applicant(17, 900m);

Console.WriteLine(IsEligible(ana));      // True
Console.WriteLine(IsEligible(teen));     // False
Console.WriteLine(IsEligible(missing));  // False, no NullReferenceException
Console.WriteLine(IsEligibleOld(ana));   // True, same answer the long way

static bool IsEligible(Applicant? a) =>
    a is { Age: >= 18 and < 70, MonthlyIncome: >= 2500m };

// The nested-if version the pattern replaces
static bool IsEligibleOld(Applicant? a)
{
    if (a != null)
    {
        if (a.Age >= 18 && a.Age < 70)
        {
            if (a.MonthlyIncome >= 2500m) return true;
        }
    }
    return false;
}

record Applicant(int Age, decimal MonthlyIncome);

go deeper

for a junior

Read { Age: >= 18 } aloud as non-null, and Age at least 18, and remember that a null input makes the whole pattern false rather than throwing.

for a middle

Explain that each subpattern receives the member's value as its input, that relational operands must be constants of a numeric, char or enum type, and how and builds a range on one member.

for a senior

In review, collapse null guards and range ifs into one pattern, keep run-time limits in ordinary comparisons, and never rely on the order in which a pattern reads properties.

for a principal

Decide where patterns help a team's rule code: when one pattern replaces an if chain, and when a named method or guard keeps business limits configurable and testable.

## What the pattern is made of `applicant is { Age: >= 18, MonthlyIncome: >= 2500m }` is one `is` expression built from two kinds of pattern: - A **property pattern** is the part in braces. It names properties or fields of the input and gives each one a nested pattern. It arrived with recursive patterns in C# 8. - A **relational pattern** is `>= 18` or `>= 2500m`: one of `<`, `<=`, `>` or `>=` followed by a constant. Relational patterns arrived in C# 9. The property pattern reads `Age` and hands its value to `>= 18`; it reads `MonthlyIncome` and hands that value to `>= 2500m`. The whole pattern matches only when the input is non-null and every subpattern matches. A subpattern can be any pattern, so the braces nest naturally: a constant (`Country: "FR"`), another property pattern, or a combination built with `and`, `or` and `not`. ## How it replaces nested ifs A loan-eligibility check written the long way needs a null guard and a cascade of comparisons: ```csharp static bool IsEligibleOld(Applicant? a) { if (a != null) { if (a.Age >= 18 && a.Age < 70) { if (a.MonthlyIncome >= 2500m) return true; } } return false; } static bool IsEligible(Applicant? a) => a is { Age: >= 18 and < 70, MonthlyIncome: >= 2500m }; ``` | Concern | Nested ifs | Property pattern | |---|---|---| | Null input | explicit `a != null` | implied by the braces | | Range on one member | `a.Age >= 18 && a.Age < 70` | `Age: >= 18 and < 70` | | Several members | one `if` or `&&` per member | one subpattern per member | | Result | statements and returns | a single `bool` expression | Both methods return the same answer for every input. The pattern keeps the rule's shape on one line, which pays off when several such rules sit side by side. ## The null check you get for free A property pattern, even an empty one, tests for null before it reads anything. That is why `{ }` on its own means "any non-null value", and why `IsEligible(null)` returns `false` instead of throwing. You do not write `a != null &&` in front of the pattern; doing so is harmless but redundant. The check applies to reference types and to `Nullable<T>`; on a non-nullable value type such as `int` there is nothing to test, so `{ }` always matches. ## What a relational pattern accepts The right-hand side of a relational pattern is restricted: - It must be a **compile-time constant**: a literal, a `const` local or field, or an enum member. A local variable, a property or a `static readonly` field fails with CS9135, "A constant value of type 'int' is expected". - Its type must have built-in relational operators: the integral types including `nint` and `nuint`, `char`, `float`, `double`, `decimal`, or an enum. A `string` operand fails with CS8781, "Relational patterns may not be used for a value of type 'string'". - Only `<`, `<=`, `>` and `>=` exist. Writing `is == 5` is CS9344 and `is != 5` is CS9345; equality is a constant pattern (`is 5`) and inequality is `is not 5`. When the limit is only known at run time, such as a minimum age read from configuration, use an ordinary comparison or a `when` guard in a switch instead of forcing it into a pattern. ## Capturing what you matched A property pattern can also declare variables. A type name before the braces adds a type test, and a name after them captures the typed input: `input is Applicant { Age: >= 18 } adult`. Inside the braces, `CreditScore: { } score` captures a member's value only when it is non-null; for an `int?` member the empty pattern unwraps the nullable, so `score` is an `int`. ## Common slips 1. Assuming the braces read properties left to right. The order in which subpatterns are checked is unspecified, and a failed match may skip the rest, so getters a pattern reads should have no side effects. 2. Writing `&&` inside the braces. `&&` is a Boolean operator; inside a pattern the combinator is `and`, and `>= 18 && < 70` does not parse. 3. Writing `or` where `and` was meant. `>= 18 or < 70` matches every integer. 4. Trying `Age: 18..70`. That is a `System.Range` expression, not a pattern, and fails with CS0029.

  • Can the minimum age in a pattern such as { Age: >= minAge } come from configuration?
    Not inside the pattern. A relational pattern's operand must be a compile-time constant; with an `int minAge` local or a `static readonly` field the SDK reports CS9135, "A constant value of type 'int' is expected". Use a `const` when the limit is fixed, and an ordinary comparison or a `when` guard when it is only known at run time.
  • Which types can a relational pattern compare?
    Types with built-in relational operators: the integral types including `nint` and `nuint`, `char`, `float`, `double`, `decimal`, and enums. A `string` operand is CS8781. A struct with its own `<` and `>` operators cannot be used either, because the operand must be a constant and no constant of that struct type exists (CS9135).
  • How do you keep the matched applicant and the value of a nullable member?
    Add a type before the braces and a name after them, and use `{ }` with a name as the subpattern: `input is Applicant { Age: >= 18, CreditScore: { } score } adult`. `adult` is typed `Applicant`, and because `{ }` unwraps an `int?`, `score` is an `int`.

  • A property pattern throws NullReferenceException when the input is null.
  • You still need a != null && in front of a is { Age: >= 18 } to be safe.
  • The value after >= in a pattern can be any local variable or static readonly field.
  • The properties in the braces are guaranteed to be read left to right, as written.
  • Use && inside the braces to combine two range checks on one property.