Logical Pattern in C#: What It Is and How to Use It
logical pattern combines multiple patterns using logical operators like and, or, and not to create complex matching conditions in switch expressions or is expressions. It helps check if a value fits multiple criteria at once in a clear and readable way.How It Works
Think of a logical pattern as a way to combine simple yes/no questions about a value into a bigger question. For example, you might want to check if a number is both even and greater than 10. Instead of writing separate checks, a logical pattern lets you combine these checks into one.
In C#, logical patterns use keywords like and, or, and not to join smaller patterns. This is like using "and", "or", and "not" in everyday language to make complex decisions. The program tests the value against these combined rules and tells you if it matches.
Example
This example shows how to use logical patterns in a switch expression to classify a number based on multiple conditions.
int number = 15; string result = number switch { > 10 and < 20 => "Between 11 and 19", <= 0 => "Zero or Negative", _ => "Other" }; Console.WriteLine(result);
When to Use
Use logical patterns when you want to check if a value meets multiple conditions at once in a clean and readable way. They are especially helpful in switch expressions or is checks where you want to combine simple tests like ranges, types, or equality.
For example, you might use logical patterns to validate user input, filter data, or handle different cases in your program based on complex rules without writing many nested if statements.
Key Points
- Logical patterns combine multiple patterns using
and,or, andnot. - They make complex condition checks easier to read and write.
- Supported in C# 9.0 and later versions.
- Commonly used in
switchexpressions andispattern matching.