C# 7.0 adds lots of new features to bring code simplification and performance. Pattern matching is one of the interesting features of C# 7.0. Pattern Matching simplifies code that is conditional on the shape of data.
Pattern matching means we can switch based on the type of data to execute one or more statements.
For example, In previous times if we want to match more than one case in switch we used to do like the following
case 11: case 12: case 13: Console.Write("greater 10"); break;
Using C# 7.0 pattern matching, we can set the range of input values in the switch cases using when. We can switch based on any type, can use pattern matching case clauses.
Let’s see an example of pattern matching,
switch (experience) { case var exp when (experience > 0 & experience < 4): Console.Write("Junior stage with {0} years of experience level", exp); break; case var exp when (experience > 10): Console.Write("Super senior stage with {0} years of experience level", exp); break; case var exp when (new List<int>() { 4, 5, 6, 7 }).Contains(experience): Console.Write("Mid level stage with {0} years of experience level", exp); break; default: Console.Write("code hits the default case"); break; }
In the above code, the first case checks the experience greater than 0 and less than 4 using pattern matching. we can check more than condition using & which is similar to the way we use in if/for loops.
In the second case, we are matching only one conditional case in switch clause.
In the third case, we are checking whether the experience value is available in the list of int values we have. At final the default case works as always, and get executes at last if no other case clauses get hits.
In this pattern matching switch cases, the order of clauses is determining which pattern needs to be validated first.
The exp variable will have the value of experience variable on the successful pass of pattern matching.
I have used VS Code for executing this code and committed the source in this repo. Have a look 🙂
Happy coding 🙂
I’ve been waiting for this for ages! I have used this kind of pattern matching in Ruby, and was hoping it would make its way into C# 🙂
LikeLiked by 1 person
Great tip Pandiyan! Just what I was looking for. However, I would like to add that you can actually use the variable “exp” instead of “experience” inside the case conditions for greater than, less than etc, since you have defined the “var exp” at the beginning of the condition. Like this:
switch (experience)
{
case var exp when (exp > 0 & exp 10):
Console.Write(“Super senior stage with {0} years of experience level”, exp);
break;
case var exp when (new List() { 4, 5, 6, 7 }).Contains(exp):
Console.Write(“Mid level stage with {0} years of experience level”, exp);
break;
default:
Console.Write(“code hits the default case”);
break;
}
Thanks
LikeLiked by 3 people