C# 9 includes new pattern matching improvements:
- Type patterns match a variable is a type
- Parenthesized patterns enforce or emphasize the precedence of pattern combinations
- Conjunctive and patterns require both patterns to match
- Disjunctive or patterns require either pattern to match
- Negated not patterns require that a pattern doesn’t match
- Relational patterns require the input be less than, greater than, less than or equal, or greater than or equal to a given constant.
These patterns enrich the syntax for patterns. Consider these examples:
public static bool IsLetter(this char c) =>
c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';
Alternatively, with optional parentheses to make it clear that and has higher precedence than or:
public static bool IsLetterOrSeparator(this char c) =>
c is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z') or '.' or ',';
One of the most common uses is a new syntax for a null check:
if (e is not null) { // ... }
Any of these patterns can be used in any context where patterns are allowed: is pattern expressions, switch expressions, nested patterns, and the pattern of a switch statement’s case label.