|
// Type patterns - Example 1 |
|
// C# 8 |
|
static int GetSpeed(Vehicle vehicle) => vehicle switch |
|
{ |
|
Bus _ => 75, |
|
Car _ => 100, |
|
_ => 50 |
|
}; |
|
// C# 9 |
|
static int GetSpeed2(Vehicle vehicle) => vehicle switch |
|
{ |
|
Bus => 75, |
|
Car => 100, |
|
_ => 50 |
|
}; |
|
|
|
// Type patterns - Example 2 |
|
// C# 8 |
|
static bool IsDannyTuple((object, object) tuple) |
|
{ |
|
return tuple is (string _, int _); |
|
} |
|
// C# 9 |
|
static bool IsDannyTuple2((object, object) tuple) |
|
{ |
|
return tuple is (string, int); |
|
} |
|
|
|
// Relational patterns - Example 1 |
|
// C# 8 |
|
static int GetTax(int muncipalityId) => muncipalityId switch |
|
{ |
|
0 => 20, |
|
int n when n < 5 => 21, |
|
int n when n <= 10 => 22, |
|
int n when n > 21 => 23, |
|
_ => 20 |
|
}; |
|
// C# 9 |
|
static int GetTax2(int muncipalityId) => muncipalityId switch |
|
{ |
|
0 => 20, |
|
< 5 => 21, |
|
<= 10 => 22, |
|
> 21 => 23, |
|
_ => 20 |
|
}; |
|
|
|
// Relational patterns - Example 2 |
|
// C# 8 |
|
bool IsLetter(char c) => c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'; |
|
// C# 9 |
|
bool IsLetter2(char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z'; |
|
|
|
// Logical patterns - Example 1 |
|
// C# 8 |
|
static int GetTax3(int muncipalityId) => muncipalityId switch |
|
{ |
|
int n when n == 0 || n == 1 => 20, |
|
int n when n > 1 && n < 5 => 21, |
|
int n when n > 5 && n != 7 => 22, |
|
7 => 23, |
|
_ => 20 |
|
}; |
|
// C# 9 |
|
static int GetTax4(int muncipalityId) => muncipalityId switch |
|
{ |
|
0 or 1 => 20, |
|
> 1 and < 5 => 21, |
|
> 5 and not 7 => 22, |
|
7 => 23, |
|
_ => 20 |
|
}; |
|
|
|
// Logical patterns - Example 2 |
|
// C# 8 |
|
static int GetSpeed3(Vehicle vehicle) |
|
{ |
|
if (!(vehicle is null)) |
|
{ |
|
if (!(vehicle is Bus)) |
|
return 100; |
|
|
|
return 70; |
|
} |
|
|
|
return 0; |
|
} |
|
// C# 9 |
|
static int GetSpeed4(Vehicle vehicle) |
|
{ |
|
if (vehicle is not null) |
|
{ |
|
if (vehicle is not Bus) |
|
return 100; |
|
|
|
return 70; |
|
} |
|
|
|
return 0; |
|
} |
|
|
|
// Logical patterns - Example 3 |
|
// C# 8 |
|
static int GetSpeed5(Vehicle vehicle) => !(vehicle is Bus) ? 100 : 70; |
|
// C# 9 |
|
static int GetSpeed6(Vehicle vehicle) => vehicle is not Bus ? 100 : 70; |
|
|
|
// Parenthesized patterns |
|
// C# 9 |
|
bool IsLetter3(char c) => c is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z'); |