By using the enhanced pattern matching introduced in C# 9.0, you can use the is operator to write value range checks, null checks, and logical operations (AND, OR) in a very intuitive and concise way.
It allows you to reduce repetitive variable descriptions that were previously done using && and ||, making conditions read like English sentences.
In this article, I will explain how to utilize the new is operator, using string classification and numeric range determination as examples.
Table of Contents
- Implementation Example: Logical and Relational Patterns
- Explanation
- Summary
Implementation Example: Logical and Relational Patterns
The following code checks if an input character (string) meets specific conditions (letters or delimiters) and performs a null check on an object.
using System;
namespace PatternMatchingExample
{
class Program
{
static void Main(string[] args)
{
// 1. String pattern matching
// Range comparison in dictionary order (>= "a" and <= "z") or checking specific values
string input = "Q";
// Traditional way:
// if ((input >= "a" && input <= "z") || (input >= "A" && input <= "Z") || input == "." || input == ",")
// Way using pattern matching:
bool isValidChar = input is (>= "a" and <= "z")
or (>= "A" and <= "Z")
or "."
or ",";
Console.WriteLine($"Is character '{input}' a valid pattern?: {isValidChar}");
// 2. Numeric range check
// Define range without repeating variables
int temperature = 25;
if (temperature is >= 20 and < 30)
{
Console.WriteLine("The temperature is comfortable (20 to under 30 degrees).");
}
// 3. Null check (not pattern)
// Can be used instead of "!= null". It is readable and safe as it is unaffected by operator overloading.
var position = new { X = 10, Y = 20 };
if (position is not null)
{
Console.WriteLine($"Position data exists: X={position.X}, Y={position.Y}");
}
}
}
}
Explanation
1. Logical Patterns
You can combine patterns using the keywords and, or, and not.
- and: Matches if both patterns are true (Logical AND).
- or: Matches if either pattern is true (Logical OR).
- not: Matches if the pattern is false (Negation).
2. Relational Patterns
Comparison operators like <, >, <=, and >= can be used as patterns. This allows range checks, previously written as variable >= min && variable <= max, to be concisely written as variable is >= min and <= max.
3. Null Check Best Practice
is not null is one of the recommended ways to check for null in C# 9.0 and later. Unlike the traditional != null, it purely checks if the reference is not null, even if the != operator is overloaded in the target class, making it safer and more reliable.
Summary
The expansion of the is operator allows you to replace complex conditional expressions with declarative and readable code.
- Range Check:
x is >= 0 and <= 100 - Exclusion Check:
y is not 0 - Composite Condition:
c is 'A' or 'B'
It is highly recommended to actively introduce this, especially in validation logic, as it greatly improves code readability.
