Relational Pattern in C#: What It Is and How to Use It
relational pattern lets you compare a value against a condition using operators like <, >, <=, and >= inside a switch or is expression. It helps write clear and concise code to check if a value fits a range or limit.How It Works
Think of the relational pattern as a way to ask simple questions about a number or value, like "Is this number bigger than 10?" or "Is it less than or equal to 5?" In C#, you can use relational patterns inside switch statements or is expressions to check these conditions directly.
It works like a filter that matches values based on their relationship to a number, using operators such as < (less than), > (greater than), <= (less than or equal), and >= (greater than or equal). This makes your code easier to read and understand, especially when you want to handle different ranges of values differently.
Example
This example shows how to use relational patterns in a switch expression to classify a number:
int number = 75; string category = number switch { < 0 => "Negative", >= 0 and < 50 => "Small", >= 50 and < 100 => "Medium", >= 100 => "Large", _ => "Unknown" }; Console.WriteLine($"Number {number} is {category}.");
When to Use
Use relational patterns when you want to check if a value falls within certain ranges or limits in a clean and readable way. This is especially useful for input validation, grading systems, or any situation where you categorize numbers or values based on size or thresholds.
For example, you might use relational patterns to decide shipping costs based on package weight, to assign letter grades based on scores, or to trigger alerts when sensor readings cross safety limits.
Key Points
- Relational patterns use comparison operators inside
switchorisexpressions. - They simplify checking if values fit within ranges or meet conditions.
- They improve code readability by replacing multiple
ifstatements. - Introduced in C# 9.0, they require .NET 5 or later.