Relational and Logical Patterns
Combine conditions in patterns.
Relational Patterns
A relational pattern compares the input against a constant using <, >, <=, or >=. It matches when the comparison is true.
Introduced in C# 9, relational patterns make range checks concise in switch arms and is expressions without writing explicit comparisons.
int temp = 18;
string level = temp switch
{
< 0 => "freezing",
< 15 => "cold",
< 25 => "mild",
_ => "hot"
};
System.Console.WriteLine(level);Relational with is
Relational patterns also work in is expressions, giving readable boolean tests.
n is > 0 reads almost like English and returns a bool you can use in conditions, assignments, or LINQ predicates.
using System;
class Program {
static void Main() {
int score = 82;
bool passed = score is >= 60;
Console.WriteLine(passed);
}
}All lessons in this course
- switch Expressions
- Type and Property Patterns
- Relational and Logical Patterns
- List and Tuple Patterns