Pattern matching
In a general way, pattern matching is a way to compare contents in predefined formats in an expression. The format is nothing but a combination of different matches.
In C# 7.0, pattern matching is a feature. With the use of this feature, we can implement method dispatch on properties other than the type of an object.
Pattern matching supports various expressions; let's discuss these with code-examples.
Note
Patterns can be constant patterns: Type patterns or Var patterns.
is expression
The is expression enables the inspection of an object and its properties and determines whether it satisfies the pattern:
public static string MatchingPatterUsingIs(object character)
{
if (character is null)
return $"{nameof(character)} is null. ";
if (character is char)
{
var isVowel = IsVowel((char) character) ? "is a
vowel" : "is a consonent";
return $"{character} is char and {isVowel}. ";
}
if (character is string)
{
var chars = ((string...