A relational pattern in C# is a pattern matching construct introduced in C# 9.0 that evaluates whether an expression satisfies a relational operator condition against a constant value. It extends 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.
is operator and switch statements/expressions by allowing direct magnitude comparisons without requiring explicit variable declarations or complex if-else chains.
Syntax and Operators
A relational pattern consists of a relational operator followed by a constant expression. The supported operators are:<(less than)<=(less than or equal to)>(greater than)>=(greater than or equal to)
Technical Constraints
- Constant Right-Hand Side: The value on the right side of the relational operator must be a compile-time constant. You cannot use variables, method returns, or dynamically evaluated expressions as the target of the pattern.
- Supported Types: Relational patterns are restricted to types that have built-in relational operators. This includes:
- All integral and floating-point numeric types (
int,double,decimal,byte,nint, etc.) charenumtypes
- All integral and floating-point numeric types (
- Nullability: If the input expression is a nullable value type (e.g.,
int?), a relational pattern implicitly checks for null. A null value will safely fail the pattern match without throwing aNullReferenceException.
Code Mechanics
The following demonstrates the structural application of relational patterns across different C# constructs:Composition with Logical Patterns
Relational patterns are strictly single-operator. To define bounded ranges, they must be composed using C# logical patterns (and, or, not). The compiler evaluates these composite patterns to ensure type safety and logical coherence.
Compiler Behavior: Subsumption and Exhaustiveness
When relational patterns are used withinswitch expressions, the C# compiler performs static analysis to verify two conditions:
- Exhaustiveness: The compiler checks if all possible values of the input type are handled. If the relational patterns leave a gap (e.g.,
< 0and> 0, leaving0unhandled) and no discard pattern (_) is provided, the compiler issues a warning (CS8509). - Subsumption (Unreachability): The compiler evaluates the order of relational patterns. If a broader pattern precedes a narrower pattern that it entirely overlaps, the compiler flags the narrower pattern as unreachable code (
CS8510).
Master C# with Deep Grasping Methodology!Learn More





