Author avatar

Gabriel Cánepa

Use Pattern Matching in Switch Statements

Gabriel Cánepa

  • Apr 29, 2019
  • 8 Min read
  • 7,465 Views
  • Apr 29, 2019
  • 8 Min read
  • 7,465 Views
Hosted
C#

Introduction

As explained in Using Conditional Statements Like If and Switch in C#, a switch statement can be used to execute different blocks of code based on the value of the control variable, also known as the match expression.

In C# 6.0 and earlier versions, the match expression could only be compared to a constant pattern - either a char, a string, a bool, a number (int or long), or an enum. Starting with C# 7.0, we can also use custom object types and their properties to define the flow of the program, a feature called pattern matching that we will discuss in this guide.

Note: You will need Visual Studio 2017 or newer to follow along. If you choose to use .NET Fiddle, be sure to use Roslyn as the compiler for your project. For your reference, the code for this guide is available in Github.

Introducing Pattern Matching

To get a grasp on the wonders of pattern matching, let us begin by considering the following Employee parent and Engineer and Developer children classes. Note that, for simplicity, we will assume the variable called name represents the employee's full name. In this example, language is the preferred programming language for a developer, and leader indicates whether the engineer currently leads a team or not.

1class Employee {
2	private string name;
3	private int age;
4	public string Name {
5		get {
6			return this.name;
7		}
8		set {
9			this.name = value;
10		}
11	}
12	public int Age {
13		get {
14			return this.age;
15		}
16		set {
17			this.age = value;
18		}
19	}
20}
21
22class Engineer: Employee {
23	private bool leader;
24	public bool Leader {
25		get {
26			return this.leader;
27		}
28		set {
29			this.leader = value;
30		}
31	}
32}
33
34class Developer: Employee {
35	private string language;
36	public string Language {
37		get {
38			return this.language;
39		}
40		set {
41			this.language = value;
42		}
43	}
44}
csharp

Next, we will create one employee, one developer, and two engineer objects:

1Employee emp = new Employee
2{
3	Name = "Mike Ehrmantraut",
4	Age = 45
5};
6
7Developer dev = new Developer
8{
9	Name = "Walter White",
10	Age = 27,
11	Language = "JavaScript"
12};
13
14Engineer eng1 = new Engineer
15{
16	Name = "Gus Fring",
17	Age = 32,
18	Leader = true
19};
20
21Engineer eng2 = new Engineer
22{
23	Name = "Hector Salamanca",
24	Age = 49,
25	Leader = false
26};
csharp

With that in mind, the following scenarios will help us illustrate the most important aspects of pattern matching.

Example 1: The Type Pattern

To begin, let us create a method called PrintPersonalInfo, which will take a generic person object as a parameter:

1public static void PrintPersonalInfo(object person)
2{
3	switch (person)
4	{
5		case Developer d:
6			Console.WriteLine($"{d.Name} is a {d.Age}-year-old developer with {d.Language} skills");
7			break;
8		case Engineer e:
9			Console.WriteLine($"{e.Name} is a {e.Age}-year-old engineer");
10			break;
11	}
12}
csharp

In the code above, we see:

  • The match expression is compared against two custom objects (Developer and Engineer). More accurately, we are checking the type of the control variable, which is the same as saying that we are using a type pattern.

  • Variable instances d and e are assigned the value of person only when the pattern is matched (which means they are in scope only within their corresponding case blocks and cannot be used outside).

If we now call PrintPersonalInfo on each object, the output show be similar to Fig. 1:

1PrintPersonalInfo(emp);
2PrintPersonalInfo(dev);
3PrintPersonalInfo(eng1);
4PrintPersonalInfo(eng2);
csharp

Figure 1 - Output of PrintPersonalInfo

You probably noticed there is no case block for the Employee object. This results in nothing being printed when the method is run as PrintPersonalInfo(emp), which leads us to what we will discuss in Example 2.

Example 2: Non-mutually Exclusive Values

To proceed, we will add the following case at the top of the switch block:

1case Employee em:
2	Console.WriteLine($"{em.Name} is one of our employees");
3	break;
csharp

When we try to compile the project, we will get a CS8120 error (The switch case has already been handled by a previous case), as shown in Fig. 2:

Figure 2 - CS8120: The switch case has already been handled by a previous case

The challenge here is that pattern matching in the switch structure opens the door for non-mutually exclusive values in separate case labels. Generally speaking, C# 7.0 and newer versions will complain if it detects a case that represents a subset of a previous statement. In this example, both Developer and Engineer are subclasses of Employee, which explains why we get the error twice in the debug window at the bottom of Fig. 2.

C# 6 and older versions only allowed mutually exclusive values through the constant pattern, so the order of the case statements was not important. That did change beginning with C# 7.0 as we can see above.

That being said, we can move the corresponding case block at the bottom of the switch section if we need to take into account the Employee object.

Example 3: Switching on Properties

For this example, let us replace the switch block in PrintPersonalInfo with the following code:

1switch (person)
2{
3	case Engineer e when e.Leader:
4		Console.WriteLine($"{e.Name} is currently leading a team");
5		break;
6	case Engineer e when !e.Leader:
7		Console.WriteLine($"{e.Name} is not leading a team these days");
8		break;
9}
csharp

Fig. 3 shows the output of calling the method on the same objects as before. As expected, it only prints a message to the screen when executed as PrintPersonalInfo(eng1) and PrintPersonalInfo(eng2):

Figure 3 - Using the when keyword in var pattern

At first sight, this example does not add much to #1 - except for the use of the when keyword that now allows us to switch on the object's properties. Similarly, we can also check if an attribute matches a pattern with the following valid case labels:

1case Engineer e when e.Name.Contains("Gus"):
csharp

or

1case Developer d when d.Language.ToUpper().Contains("JAVASCRIPT"):
csharp

In example #2, we could also have used the when keyword as case Employee em when !(em is Developer || em is Engineer) to leave the associated block at the top of the switch section.

Of course, this also means that you can potentially use more complex regular expressions as conditions. Checking a string for a given substring is presented here as a representative illustration.

Summary

In this guide, we have examined the basics of pattern matching in switch statements. This feature gives us more flexibility by allowing us to use any non-null expression in match expressions. However, since with great power comes great responsibility, be sure to address non-mutually exclusive conditions. You can accomplish that goal by placing case blocks in the right order or using the when keyword as explained here.