Skip to main content
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 the 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

  1. 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.
  2. 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.)
    • char
    • enum types
  3. 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 a NullReferenceException.

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 within switch expressions, the C# compiler performs static analysis to verify two conditions:
  1. Exhaustiveness: The compiler checks if all possible values of the input type are handled. If the relational patterns leave a gap (e.g., < 0 and > 0, leaving 0 unhandled) and no discard pattern (_) is provided, the compiler issues a warning (CS8509).
  2. 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).
Tired of Poor C# Skills? Fix That With Deep Grasping!Learn More