C# 7.0 – Pattern Matching in Switch

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");

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);

      case var exp when (experience > 10):
         Console.Write("Super senior stage with {0} years of experience level", exp);

     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);

         Console.Write("code hits the default case");

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 🙂

2 thoughts on “C# 7.0 – Pattern Matching in Switch

  1. Steven Atkinson August 30, 2017 / 2:14 pm

    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# 🙂

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s