1) if/else Pattern Matching (C# 7.0)
Use “is” keyword to check the type of an object
Example:
static void FindPattern()
{
object item1 = 10;
object item2 = "Hello!";
if(item1 is int value1)
{
Console.WriteLine($"{item1} is an integer.");
}
if(item2 is string value2)
{
Console.WriteLine($"The string is {value2}");
}
}
Pattern Matching Improvements in C# 9.0
Pattern | Remark |
---|---|
Type patterns | if (t is Type) |
Parenthesized patterns | if(a is (…) or (…)) |
And patterns | if(a is (…) and (…)) |
Or patterns | if( a is … or …) |
Not patterns | if( a is not string), if( a is not null) |
Relational patterns | if( a is > b) |
2) switch Pattern Matching (C# 7.0)
Besides constant pattern, switch statements can also have type pattern.
static void SwitchPattern()
{
object obj = 1;
switch (obj)
{
// Type is checked first and value is also checked using when clause.
case int i when i!=0:
Console.WriteLine($"The object is an integer not equal to zero: {i}");
break;
case string s when s.Equals(""):
Console.WriteLine($"The object is a string not empty: {s}");
break;
case long l:
Console.WriteLine($"The object is long number: {l}");
break;
default:
Console.WriteLine("Else");
break;
}
}