Is it me or Functional programming (FP) seems to be trending lately? FP languages like Haskell, Elixir, and F# are stronger than ever and large frameworks try to adopt a more functional approach. Even C# tries to include functional constructs in the language. As a matter of fact, one of the biggest addition in the latest version of C# (8.0) is pattern matching. Pattern matching is not really new in C# though. So far, it was pretty basic and felt like it was more of a second class citizen. With the latest release of C#, we now have full support for it. Let's dive in! Pattern matching is achieved by using the operator. Wait a minute... doesn't already exist in the language? Yes, which makes the adoption of this new feature very confusing. switch switch Even if the keyword, syntax, and behavior of the operator are similar, the new feature differs remarkably. One of the biggest differences is that the new is an expression and the old one is a statement. You don't have case and break statements anymore. switch switch Expression vs Statement A quick note before we continue. For most people, the difference between a statement and an expression is very unclear. Here's the best definition I've found so far. : Something which returns a value when evaluated : A line of code executing something Expression Statement e.g. Statement (a == ) { someCode... } { someCode2... } if null else Expression a == ? value1 : value2; null That being said That being said, let's explore the similarities and differences between the 2 operators. switch Old switch Syntax ( ) { : something... ; : something2... : something3... ; : somethingDefault.... ; } switch value case 1 break case 2 case 3 break default break The old switch tries to find the next instruction to branch to. Then it executes every line sequentially until it hits a break statement. It behaves like a statement, which is generally considered a bad practice. This operator only runs code and doesn't return anything, that's why it's considered a statement. goto New switch Syntax a = value1 { matchingExpression => expression matchingExpression2 => expression ... } var switch On the other hand, the new switch must return a value. In fact, every possible match must return a value of the same type. Matching expressions can use patterns to match or not. Hence the name pattern matching. The power of patterns Matching patterns not only match when a condition is true but also cast your object to the matched type and assign it to a variable automatically. From there you can match on the object properties and even evaluate boolean expressions on those properties. Nothing better than some examples Let's explore a application that has many business rules. We'll see how pattern matching makes the code clean and easy to read. TollService V1 - Matching on types { vehicle { Car c => m, Taxi t => m, Bus b => m, DeliveryTruck t => m, { } => ArgumentException( , (vehicle)), => ArgumentNullException( (vehicle)) }; } ( ) public decimal CalculateToll vehicle object // Price per vehicle type // ========== // Car -> 2$ // Taxi -> 3.50$ // Bus -> 5$ // Truck -> 10$ return switch 2.00 3.50 5.00 10.00 throw new "Not a known vehicle type" nameof null throw new nameof V2 - Matching on properties You can use the to match on specific values of your object {} { vehicle { Car { Passengers: } => m + m, Car { Passengers: } => m, Car { Passengers: } => m - m, Car _ => m - m, Taxi { Fares: } => m + m, Taxi { Fares: } => m, Taxi { Fares: } => m - m, Taxi _ => m - m, Bus b => m, DeliveryTruck t => m, { } => ArgumentException( , (vehicle)), => ArgumentNullException( (vehicle)) }; } ( ) public decimal CalculateToll vehicle object // Price considering occupancy // =========== // Car and taxi // No passengers -> +0.50 $ // 2 passengers -> -0.50 $ // 3 or more passengers -> -1$ return switch 0 2.00 0.50 1 2.0 2 2.0 0.50 2.00 1.0 0 3.50 1.00 1 3.50 2 3.50 0.50 3.50 1.00 5.00 10.00 throw new "Not a known vehicle type" nameof null throw new nameof V3 - Conditional boolean expression You can use the keyword to define a boolean expression that will be evaluated on your object. You may already be familiar with the keyword. It was previously introduced in C# 6.0 in statements to evaluate conditions on properties of the exception. As you can imagine, it works exactly the same way here, so you shouldn't be lost. when when catch { vehicle { => m + m, => m - m, Bus _ => m, DeliveryTruck t => m, { } => ArgumentException( , (vehicle)), => ArgumentNullException( (vehicle)) }; } ( ) public decimal CalculateToll vehicle object // Price considering occupancy // =========== // Bus // Less than 50% full -> +2$ // More than 90% full -> -1$ return switch // car and taxi hidden here to make it easier to read // ... Bus b ( )b.Riders / ( )b.Capacity < 0.50 when double double 5.00 2.00 Bus b ( )b.Riders / ( )b.Capacity > 0.90 when double double 5.00 1.00 5.00 10.00 throw new "Not a known vehicle type" nameof null throw new nameof V4 - Nesting operators must return an expression and since they are themselves expressions, it means we can nest them to make our code easier to read. switch { vehicle { Car c => c.Passengers { => m + m, => m, => m - m, _ => m - m }, Taxi t => t.Fares { => m + m, => m, => m - m, _ => m - m }, }; } ( ) public decimal CalculateToll vehicle object return switch switch 0 2.00 0.5 1 2.0 2 2.0 0.5 2.00 1.0 switch 0 3.50 1.00 1 3.50 2 3.50 0.50 3.50 1.00 // Bus and truck hidden here to make it easier to read // ... Special match expressions You may have noticed in the previous examples that we've been using some special matching expressions, , and . {} null _ : Non-null, but an unknown type {} : null value null : Wildcard that matches absolutely anything but doesn't capture the value in a new variable _ Gotcha Matching expressions are evaluated from top to bottom. Always put the most restrictive matching expression first and try to finish with the 'special' match expressions. e.g. If you use _ as the first line, it will always match on this expression and nothing else will be evaluated. Closing word Pattern matching is super powerful and can be used to simplify complex business logic while making it easier to read. Stay tuned for more blog posts in this series! All code samples are available on github References https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/pattern-matching Previously published at https://blog.miguelbernard.com/pattern-matching-in-csharp/