A logical pattern in C# is a pattern matching construct that combines or negates other patterns using theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
and, or, and not pattern combinators. Introduced in C# 9.0, it allows the evaluation of multiple pattern matching conditions within a single expression, operating directly on patterns rather than evaluating standard boolean expressions. Logical patterns are exclusively utilized within pattern matching contexts, such as the is operator, switch statements, and switch expressions.
Pattern Combinators
Logical patterns utilize three specific contextual keywords. They are distinct from standard boolean logical operators (&&, ||, !) because they compose patterns rather than evaluating boolean variables.
1. The not Pattern (Negation)
The not pattern matches an expression if the negated pattern does not match the expression. It is frequently applied to constant patterns and type patterns.
2. The and Pattern (Conjunction)
The and pattern matches an expression if both of the combined patterns match the expression. It is commonly used to combine relational patterns to define boundaries.
3. The or Pattern (Disjunction)
The or pattern matches an expression if either of the combined patterns matches the expression. It is typically used to match against multiple discrete constant patterns or distinct type patterns.
Operator Precedence and Grouping
When combining multiple logical patterns, the C# compiler enforces a strict order of precedence. From highest to lowest precedence, the order is:notandor
() are used to explicitly group patterns.
Composition with Other Patterns
Logical patterns act as a structural glue for other pattern types. They can compose:- Constant patterns:
is 1 or 2 - Relational patterns:
is > 0 and < 10 - Type patterns:
is int or double - Property patterns:
is { Length: > 0 } and not { Length: 5 } - Declaration patterns:
is int x and > 0(Note: C# strictly prohibits declaring variables insideorandnotpatterns. Attempting to do so results in compiler error CS8780).
Master C# with Deep Grasping Methodology!Learn More





