Switch Expressions And Pattern Matching

In this article, we will go through the Switch expressions and Pattern matching.
 
Switch expression has evolved over a few releases and in C# 8, it has changed significantly. In the new switch expression, repetitive case and break keywords have been significantly reduced.
 
Let's have a look at both the traditional and new switch expressions to understand the changes. We will start with a traditional expression as follows.
  1. private static RGBColor ExecuteOldSwitch(PrimaryColor color)  
  2. {  
  3.    switch (color)  
  4.    {  
  5.       case PrimaryColor.Red:  
  6.       return new RGBColor(0xFF, 0x00, 0x00); case PrimaryColor.Green:  
  7.       return new RGBColor(0x00, 0xFF, 0x00); case PrimaryColor.Blue:  
  8.       return new RGBColor(0x00, 0x00, 0xFF); default:  
  9.       throw new ArgumentException(message: "invalid color", paramName: nameof(color));  
  10.    };  
  11. }  
Now let's look at the modern switch statement introduced in C# as follows.
  1. private static RGBColor ExecuteNewSwitch(PrimaryColor color) => color switch  
  2. {  
  3.    PrimaryColor.Red => new RGBColor(0xFF, 0x00, 0x00), PrimaryColor.Green => new RGBColor(0x00, 0xFF, 0x00), PrimaryColor.Blue => new RGBColor(0x00, 0x00, 0xFF),  
  4.    _ => throw new ArgumentException(message: "invalid color", paramName: nameof(color))  
  5. };  
You may have noticed that new switch syntax is crisper and intuitive. The summary of changes can be put together as follows.
  • The variable name comes before the switch.
  • The case and : elements are replaced with =>.
  • The default case has been replaced with a _ discard.
  • The bodies are no more statements but expressions.
There are some additional patterns emerged out of new switch statements like property, tuple and positional patterns. Let's have a look at them one by one.
 

Property Pattern

 
Property pattern helps you to compare the properties of the object.
 
Consider a government tax calculation site that must calculate tax based on the buyer's address. In this case, the tax amount depends on the State property of the address. The following example uses the property pattern to compute the tax from the address along with the overall price.
  1. public static void ExecutePropertyPattern()  
  2. {  
  3.    Address address = new Address{ State = "MN"}; Console.WriteLine($"Overall price (including tax) of  
  4.    {address.State} is: {ComputeOverallPrice(address, 2.4M)}");  
  5. }  
  6. private static decimal ComputeOverallPrice(Address location, decimal price)  
  7. =>  
  8. location switch  
  9. {  
  10.    { State: "MN" } => price + price * 0.78M,  
  11.    { State: "MI" } => price + price * 0.06M,  
  12.    { State: "WA" } => price + price * 0.07M,  
  13.    _ => 0M  
  14. };  

Tuple Pattern

 
Now let's have a look at the tuple pattern, it’s like property pattern with a difference in that it uses tuple values to compare.
 
Let's have a look at the example as follows.
  1. public static void ExecuteTuplePattern()  
  2. {  
  3.    (stringstringstring) counties = ("India""Australia","England");  
  4.   
  5.    var team1 = counties.Item1.ToString();   
  6.    var team2 = counties.Item3.ToString();  
  7.    Console.WriteLine($"Result of the match between {team1} and {team2} is: {ReturnWinner(team1, team2)}");  
  8. }  
  9.   
  10. private static string ReturnWinner(string team1, string team2)  
  11. => (team1, team2) switch  
  12. {  
  13.    ("India""Australia") => "Australia is covered by India. India wins.",  
  14.    ("Australia""England") => "Australia breaks England. Australia wins.",  
  15.    ("India""England") => "India covers England. India wins.",  
  16.    (_, _) => "tie"  
  17. };  
As you can see in the above code the tuple value is being compared and the expression of matching tuple value is being returned to the caller. In the above example, the output would be displayed as "Result of the match between India and England is: India covers England. India wins."
 

Positional Pattern

 
Apart from properties and tuples, patterns can be matches even for positions. Positional pattern matching works with the help of deconstructor introduced in C# 7.
 
Deconstructor allows setting its properties into discrete variables and allows the use of positional patterns in a compact way without having to name properties.
 
Let's take an example to understand it more. To start with let's create a Point class that uses the deconstruct method.
  1. public class Point  
  2. {  
  3.    public int X { get; } public int Y { get; }  
  4.    public Point(int x, int y) => (X, Y) = (x, y); public void Deconstruct(out int x, out int y)  
  5.    {  
  6.       (x, y) = (X, Y);  
  7.    }  
  8. }  
Please note that here method name Deconstruct is required by the compiler and any other name with the same method body won't work.
 
We also need to have an enum to facilitate the positional comparison as follows.
  1. public enum Quadrant  
  2. {  
  3.    Origin, One,   
  4.    Two, Three, Four,  
  5.    OnBorder, Unknown  
  6. }  
Now let's have logic to find patterns and a method to call it and print on console.
  1. public static void ExecutePositionalPattern()  
  2. {  
  3.    Point point = new Point(5,10);  
  4.    Console.WriteLine($"Quadrant of point {point.X} and {point.Y} is: {FindQuadrant(point)}");  
  5. }  
  6.   
  7. private static Quadrant FindQuadrant(Point point) => point switch  
  8. {  
  9.    (0, 0) => Quadrant.Origin,  
  10.    var (x, y)  when    x   >    0   &&  y   >    0   =>   Quadrant.One,  
  11.    var (x, y)  when    x   <    0   &&  y   >    0   =>   Quadrant.Two,  
  12.    var (x, y)  when    x   <    0   &&  y   <    0   =>   Quadrant.Three,  
  13.    var (x, y)  when    x   >    0   &&  y   <    0   =>   Quadrant.Four,  
  14.    var (_, _) => Quadrant.OnBorder,  
  15.    _ => Quadrant.Unknown  
  16. };  
The above code will output as "Quadrant of point 5 and 10 is: One" as passed points 5 and 10 falls in the first quadrant.
 
In the code above, the discard pattern (_) matches when either x or y is 0, but not both. An important point with switch expression is that it must either produce a value on matching cases or throw an exception if none of the cases match. Also, the compiler renders a warning if you do not include all possible cases in your switch expression.
 
Note
Deconstruction isn't a great choice and it should only be used to types where it makes sense and clearer to interpret. For example, for a Point class, it was easy and intuitive to assume that the first value is X and the second is Y, so please use positional patterns carefully.
 

Summary

 
In this article, we have gone through the new switch syntax and compared it with the traditional one. We have also understood how patterns (property, tuple and positional) can be used with a switch to make it even more powerful. Clearly new switch syntax is more crisp and easy to use.
Author
Prakash Tripathi
29 40.3k 6.3m
Next » Ranges And Indices