Another interesting set of features introduced in C# 7.0 is related to patter matching. Pattern matching is a well-known concept in functional programming languages and in a nutshell, it allows to test data against some “pattern” (for example test if data belongs to some type) and to extract values from complex data (deconstruct). In many cases pattern matching allows to replace a series of if, else and assignment statements with a single expression.
To support pattern matching, C# 7.0 extends use of is and case keywords and allows to use constants and types as the patterns. The simple use of the pattern matching is to match a value against some constant:
public void UltimateQuestion(object x)
{
if (x is 42)
{
Console.WriteLine("This is the answer");
}
}
More interesting use is to test for the type and to create a new variable of that type
public void UltimateQuestion(object x)
{
if (x is null)
return;
if (!(x is int i))
return;
Console.WriteLine(i < 42 ? "Ask one more time" : "42 is the answer");
}
Similarly, patterns can be matched using switch statement:
switch (animal)
{
case Dog d:
break;
case Cat c when c.Color == "White":
break;
case null:
Console.WriteLine("No animal");
break;
default:
Console.WriteLine("Unknown animal");
break;
}
Notes
Unlike Haskel or Elixir where pattern matching is engraved into the language, C# implementation of pattern matching does not feel at the moment fully integrated with the language. It could be because of the limited number of patterns available to use or a loos link between pattern matching and deconstruction, but anyway it is a promising start which requires some improvements in the next releases.
blog comments powered by Disqus