0
0
CsharpConceptBeginner · 3 min read

Relational Pattern in C#: What It Is and How to Use It

In C#, a 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:

csharp
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}.");
Output
Number 75 is Medium.
🎯

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 switch or is expressions.
  • They simplify checking if values fit within ranges or meet conditions.
  • They improve code readability by replacing multiple if statements.
  • Introduced in C# 9.0, they require .NET 5 or later.

Key Takeaways

Relational patterns let you compare values using operators like <, >, <=, >= inside pattern matching.
They make code cleaner and easier to read when checking value ranges.
Use them in switch expressions or is statements to handle different value categories.
Relational patterns require C# 9.0 or newer and .NET 5 or later.