Pattern-matching improvements
2022-10-23T07:33:39 - Vicky Chhetri
Read Time:36 Second
The relational pattern allows the <, >, <=, and >= operators to appear in patterns:
string GetWeightCategory (decimal bmi) => bmi switch {
< 18.5m => "underweight",
< 25m => "normal",
< 30m => "overweight",
_ => "obese" };
With pattern combinators, you can combine patterns via three new keywords (and, or, and not):
bool IsVowel (char c) => c is 'a' or 'e' or 'i' or 'o' or 'u';
bool IsLetter (char c) => c is >= 'a' and <= 'z'
or >= 'A' and <= 'Z';
As with the && and || operators, and has higher precedence than or. You can override this with parentheses.
The not combinator can be used with the type pattern to test whether an object is
(not) a type:
if (obj is not string) ...