skip to content

Pattern Syntax

Type, property, relational, logical and list patterns let is and switch test shape and value at once. Interviewers ask how exhaustiveness and arm order work.

on this pageshow

explore

questions

20

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.
open as a page

In C#, how do you write a switch expression mapping an OrderStatus enum to a label, and how does it differ from a switch statement?

level: juniorimportance: must knowfreq 75%

basics

~20 s

A switch expression is written status switch { OrderStatus.Paid => "Paid", _ => "Other" }: comma-separated pattern => expression arms, tried in text order. Unlike a switch statement it produces a value, so each arm is an expression, never a statement block.

open as a page

In C#, what does `if (payload is TextMessage text)` test and assign when payload is an object, and which values make it match?

level: juniorimportance: must knowfreq 80%

basics

~20 s

An is test with a declaration pattern checks at run time that payload is non-null and holds a TextMessage or a subclass, then declares text holding that reference. Null and unrelated types never match, and no conversion operator runs.

open as a page

In a C# switch expression over a (carrier, band) tuple, which arm wins when several match, and how do when guards affect error CS8510?

level: middleimportance: must knowfreq 62%

basics

~20 s

The first arm in text order whose pattern matches and whose when guard is true wins. An arm an earlier unguarded arm covers is error CS8510; a guard such as when kg > 20 keeps lower arms reachable, since it may fail.

open as a page

In C#, how does `payload as TextMessage` followed by a null check differ from `payload is TextMessage text`, and where will as not compile?

level: middleimportance: must knowfreq 66%

basics

~20 s

The as form and the is pattern run the same run-time type test, but as yields null on failure, needs a separate null check and rejects non-nullable value types (CS0077). The is pattern tests and declares in one step.

open as a page

In C#, why does `args is ["--help"]` return false for an empty array while `args[0] == "--help"` throws?

level: juniorimportance: should knowfreq 45%

basics

~20 s

A C# list pattern without a slice tests the element count first, so ["--help"] needs exactly one element and an empty array simply fails the match. Indexing args[0] reads an element with no length check and throws IndexOutOfRangeException.

open as a page

In C#, how do you nest patterns inside a list pattern to recognise CSV comment, header and data rows held in a string[]?

level: middleimportance: should knowfreq 40%

basics

~20 s

Each position of a C# list pattern takes any pattern: in a CSV row check, [['#', ..], ..] means the first cell starts with '#', and [_, .., { Length: 0 }] means at least two cells with an empty last one.

open as a page

In a C# argument parser, how does the switch arm `["deploy", var env, .. var rest]` match argv, and what does rest hold?

level: middleimportance: should knowfreq 50%

basics

~20 s

The arm matches a non-null string[] of two or more elements starting with "deploy"; env binds index 1, and .. var rest binds the remaining elements as a new string[], empty when argv has exactly two.

open as a page

In C#, what does the extended property pattern `{ Employment.Years: >= 2 }` mean, and what happens when Employment is null?

level: middleimportance: should knowfreq 45%

basics

~20 s

It is C# 10 shorthand for the nested pattern { Employment: { Years: >= 2 } }: Employment must be non-null and its Years at least 2. A null Employment makes the pattern false; nothing throws.

open as a page

In C#, how does a positional pattern such as `applicant is (>= 18, >= 2500m)` obtain the values it tests, and when does it compile?

level: middleimportance: should knowfreq 40%

basics

~20 s

A positional pattern null-checks the input, calls a Deconstruct with one out parameter per position, or reads a tuple's elements, and matches each value in order. Without such a Deconstruct it fails with CS8129, unless the input is a tuple, object or ITuple.

open as a page

How does the C# compiler decide the type of a switch expression whose arms return different types, such as an int and a null?

level: middleimportance: should knowfreq 38%

basics

~20 s

A switch expression takes the best common type of its arms when one exists. Otherwise, as with an int arm and a null arm, it takes the type it is converted to; var supplies none, so the compiler reports CS8506.

open as a page

In C#, why is `receipt is 42` false when the object receipt holds a boxed 42L, and what do `is var x` and `is var _` match?

level: middleimportance: should knowfreq 38%

basics

~20 s

For an object input, the constant pattern 42 matches only a boxed int equal to 42; a boxed long never does, because no numeric conversion runs. The var pattern matches every value, null included, and var _ matches anything without naming it.

open as a page

In C#, why does `rows is [var first, ..]` fail to compile when rows is an IEnumerable<string>, and what must a type provide?

level: seniorimportance: should knowfreq 35%

basics

~20 s

List patterns need a countable, indexable compile-time type: an accessible Length or Count property and an indexer taking Index or int. IEnumerable<string> has neither, so the compiler reports CS8985. Capturing a slice also needs a Range indexer or a Slice(int, int) method.

open as a page

In C#, why does `status is not EmploymentStatus.Unemployed or EmploymentStatus.Student` still accept students, and what does the compiler report?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Pattern combinators bind not first, then and, then or, so this means (not Unemployed) or Student, which every student already matches on the left. At C# 14 the compiler flags the redundant Student with warning CS9336; write not (Unemployed or Student).

open as a page

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%

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.

open as a page

After a teammate adds OrderStatus.Cancelled, what happens to a C# switch expression that lists the other statuses with no discard arm, at compile time and at run time?

level: seniorimportance: should knowfreq 48%

basics

~20 s

The build still succeeds but warns CS8509, naming OrderStatus.Cancelled as uncovered. At run time a Cancelled order matches no arm and throws SwitchExpressionException, whose UnmatchedValue is Cancelled. A discard arm would have hidden both signals.

open as a page

In a C# chat dispatcher, why does `if (message == null) return;` drop blank messages once Message overloads operator ==, while `is null` does not?

level: seniorimportance: should knowfreq 48%

basics

~20 s

message == null calls Message's user-defined operator ==, whose rule treats a blank message as equal to null, so the guard returns early. message is null compiles to a plain reference comparison and never calls a user-defined operator.

open as a page

In C#, why does `payload is TextMessage text || payload is null` leave text unusable in the if body, while `payload is not TextMessage text` followed by return does not?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A pattern variable is definitely assigned only where its test succeeded. With ||, the body also runs when that test failed, so reading text is error CS0165; after an is not test that returns, only matching payloads reach the next line.

open as a page

Should a team price Parcel, Pallet and Letter shipments with a C# switch expression over the Shipment types or an abstract Rate method, and should CS8509 fail the build?

level: principalimportance: should knowfreq 30%

basics

~20 s

C# cannot prove a type switch over a class hierarchy exhaustive, so a new Letter class compiles and fails at run time; an abstract Rate method fails the build with CS0534. Choose by what changes more often.

open as a page

In a hot C# parsing loop, what does a slice capture `.. var rest` allocate for a string[], a List<T>, a string and a span?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

A captured slice copies for a string[] (RuntimeHelpers.GetSubArray), a List<T> (Slice calls GetRange) and a string (Substring), but a Span<T> or ReadOnlySpan<T> slice is a view over the same memory. A bare .. creates no slice and allocates nothing.

open as a page