C# language feature:
applies to
benefit
how to use
is
statement, insert type after is
followed by variable identifier, use variable in statement as desired.switch
statement, insert type after case followed by variable identifier, use variable in case statement as desired.example:
void Is_Pattern_Matching_Example(object object2check)
{
if (object2check is int i || (object2check is string s && int.TryParse(s, out i)))
System.Console.WriteLine($"the int is {i}");
else
System.Console.WriteLine("not an int or parsable string");
}
void Switch_Pattern_Matching_Example(object object2check)
{
switch (object2check)
{
case int i:
System.Console.WriteLine($"object is an integer with value {i}");
break;
case string s:
System.Console.WriteLine($"object is a string ({s}) and has {s.Length} character(s)");
break;
default:
System.Console.WriteLine("object is something other than int or string");
break;
case null:
System.Console.WriteLine("object is null");
break;
}
}