skip to content

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%

answer

  1. position, not name
  2. out parameters, one per subpattern
  3. tuples need no method
  4. object input: an interface at run time

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.

solid answer

~40 s

A **positional pattern** matches values by position, not by name. For a class or struct the compiler needs an accessible `Deconstruct` method, instance or extension, with one `out` parameter per subpattern; at run time it checks the input for null, calls `Deconstruct` and matches each result against its subpattern. Tuples match element by element with no method, which makes `(age, income) switch { (< 18, _) => ..., (_, < 2500m) => ... }` a common way to flatten nested ifs. When the input is typed `object` or `ITuple`, the match goes through `System.Runtime.CompilerServices.ITuple` at run time. A type with no suitable `Deconstruct` is CS8129, and a name written in a position must match that `Deconstruct` parameter's name (CS8517).

code

csharp · 28 lines
csharp
var ana = new Applicant(34, 4200m);
Console.WriteLine(Decide(ana));                       // [Deconstruct] eligible
Console.WriteLine(Decide(new Applicant(17, 5000m)));  // [Deconstruct] too young

int age = 34; decimal income = 1800m;
Console.WriteLine((age, income) is (>= 18, >= 2500m));   // False, a tuple pattern

object boxed = (34, 4200m);
Console.WriteLine(boxed is (>= 18, >= 2500m));           // True, matched through ITuple

static string Decide(Applicant a) => a switch
{
    (< 18, _) => "too young",
    (_, < 2500m) => "income too low",
    _ => "eligible",
};

class Applicant(int age, decimal income)
{
    public int Age { get; } = age;
    public decimal Income { get; } = income;

    public void Deconstruct(out int age, out decimal income)
    {
        Console.Write("[Deconstruct] ");
        (age, income) = (Age, Income);
    }
}

go deeper

for a junior

Know that (>= 18, >= 2500m) compares the first and second values of the input by position, and that tuples support it directly.

for a middle

Explain where the values come from, Deconstruct, a tuple or ITuple, and the diagnostics for a missing method or a wrong name.

for a senior

Use tuple patterns to turn nested rule ifs into readable tables, and keep Deconstruct free of side effects because the compiler may cache and reorder its calls.

for a principal

Set a team rule for when positional matching is clear enough, such as small records and local tuples, and when member names should be spelled out.

## Position instead of name A **property pattern** identifies each value by a member name: `{ Age: >= 18 }`. A **positional pattern** identifies values by their order: `(>= 18, >= 2500m)` means "the first value is at least 18 and the second is at least 2500". It is a recursive pattern, so each position takes any nested pattern: a constant, a relational pattern, a discard `_`, a combination with `and` or `or`, or another positional or property pattern. ## Where the values come from The compiler picks the source of the values from the input's static type: 1. **A `Deconstruct` method.** When the type has an accessible `Deconstruct` with a `void` return and one `out` parameter per subpattern, instance or extension, the pattern null-checks the input, calls it and matches each `out` value in order. A positional record gets such a method generated; any other class or struct declares one itself. 2. **A tuple type.** A value tuple such as `(int, decimal)` matches element by element, with no method call. 3. **`object` or `ITuple`.** When the input is typed `object` or `System.Runtime.CompilerServices.ITuple`, and no member names appear in the subpatterns, the match goes through `ITuple` at run time: the runtime type must implement it (every `ValueTuple` does), its `Length` must equal the number of positions, and each element is matched through its indexer. If none of the three applies, the pattern is a compile-time error. A type name before the parentheses adds a type test first: `obj is Applicant(>= 18, _)` tests for `Applicant` and then uses `Applicant.Deconstruct`. A positional pattern with a single position needs that type name or a designation, because `(>= 18)` alone reads as a parenthesized relational pattern. ## What the compiler checks | Situation | SDK result | |---|---| | No `Deconstruct` with the right number of `out` parameters | CS8129, "No suitable 'Deconstruct' instance or extension method was found for type 'Rate', with 2 out parameters and a void return type." | | A position named differently from its `Deconstruct` parameter | CS8517, "The name 'Months' does not match the corresponding 'Deconstruct' parameter 'Amount'." | | Names used while matching through `ITuple` | CS8522, "Element names are not permitted when pattern-matching via 'System.Runtime.CompilerServices.ITuple'." | | A subpattern whose constant does not fit that position's type | for example CS0266 when `> 10000m` lands on an `int` position | Names never reorder positions. In `Loan(Months: <= 12, Amount: > 10000m)` the names are checked against the parameters at those positions, and both are CS8517. ## Tuple patterns flatten rule tables The most common use in rule code is to build a tuple on the spot and switch on it: ```csharp static string Decide(int age, decimal income) => (age, income) switch { (< 18, _) => "too young", (_, < 2500m) => "income too low", _ => "eligible", }; ``` Each row reads as one rule, and adding a dimension means adding a position. How arms are ordered and when a switch is exhaustive is the material on switch expression arms; the positional part only decides what each position is compared with. ## Calls and evaluation order The C# 8 pattern design leaves the order in which subpatterns run unspecified, and its design notes allow the compiler to reorder `Deconstruct` calls, property reads and `ITuple` calls, and to assume they return the same values each time. With the .NET 10 SDK, a three-arm switch over a class whose `Deconstruct` logs a line logs once per evaluation. Two consequences: - keep `Deconstruct` cheap and free of side effects; - never write a pattern whose result depends on how many times, or in which order, `Deconstruct` runs. ## Property or positional? - Choose a **positional** pattern when order already carries the meaning: a tuple built for one decision, or a small positional record such as `Loan(decimal Amount, int Months)`. - Choose a **property** pattern when names explain the test, when the type has many members, or when the order of `Deconstruct` parameters is not obvious to a reader. - Mix them when useful: `Loan(> 10000m, _) { Months: <= 12 } big` runs the positional part, then the property part, and captures the loan. A designation goes after the last pattern part; putting it between them is CS8525.

  • Can you name the positions, as in applicant is (age: >= 18, income: _)?
    Yes, when the values come from `Deconstruct` or a tuple: each name is checked against the parameter or element name at that position, and a mismatch is CS8517. Names do not reorder anything. When the match goes through `ITuple`, names are not allowed at all and the SDK reports CS8522.
  • How many times is Deconstruct called in a switch expression whose arms are all positional?
    The language does not fix the number: the compiler may reorder and cache `Deconstruct` calls and assume they return the same values. With the .NET 10 SDK a three-arm switch logs one call per evaluation. Keep `Deconstruct` free of side effects so the count never matters.
  • How do you combine a type test, a positional pattern and a property pattern?
    Write the type, then the positional part, then the braces, then the designation: `obj is Loan(> 10000m, _) { Months: <= 12 } big`. The type test runs first, `Loan.Deconstruct` supplies the positions, and `big` is a `Loan`. A designation placed before the braces is CS8525.

  • A positional pattern reads public properties in declaration order when there is no Deconstruct.
  • Positional patterns work on any class by matching its constructor parameters.
  • Names such as (age: >= 18, income: _) can list the positions in any order.
  • Matching an object-typed variable against (>= 18, >= 2500m) is always a compile error.
  • Deconstruct is guaranteed to run once per arm, in the order the arms are written.