Skip to main content
A parenthesized pattern is a pattern matching construct in C# that encloses an existing pattern within parentheses (). Its primary function is to explicitly define the order of evaluation and enforce grouping within complex logical patterns, overriding the default precedence of the and, or, and not pattern combinators.

Syntax

The <pattern> can be any valid C# pattern, including relational patterns, type patterns, property patterns, or other logical patterns.

Mechanics and Precedence

In C# pattern matching, logical combinators are evaluated based on a strict default precedence:
  1. not (Highest)
  2. and
  3. or (Lowest)
When a compiler evaluates a compound pattern without parentheses, it binds not first, then groups and patterns, and finally evaluates or patterns. The parenthesized pattern forces the compiler to evaluate the enclosed pattern as a single, isolated unit before applying adjacent combinators.

Altering and / or Precedence

Without parentheses, and binds tighter than or. Parentheses invert this relationship by grouping the or condition.

Grouping with not

The not combinator only negates the immediately following pattern. To negate a compound logical pattern, the parenthesized pattern is required to encapsulate the entire expression.

Nesting

Parenthesized patterns can be nested arbitrarily deep to construct highly specific evaluation trees. The innermost parentheses are evaluated first.

Interaction with Declaration Patterns

When a parenthesized pattern contains a declaration pattern (which assigns a matched value to a variable), the compiler enforces strict rules regarding variable declarations across logical combinators. Specifically, if a parenthesized declaration pattern is used as a branch within an or pattern, the exact same variable (matching both name and type) must be declared in all branches of that or pattern. Failure to declare the variable in every branch results in a hard compiler error, as the compiler dictates that any variable introduced in an or pattern must be guaranteed to be initialized regardless of which branch succeeds.
Tired of Poor C# Skills? Fix That With Deep Grasping!Learn More