This is part 3 in a series of articles.

In the first part of this series we looked at switch expressions.

When making use of switch expressions, C## 8 also introduced the concept of property pattern matching. This enables you to match on one or more items of an object and helps to simplify multiple **if…else if **statements into a more concise form.

For example, suppose we had a CustomerOrder:

Now say we wanted to calculate a delivery cost based on what State the order is being delivered to. If the customer is a VIP member then the delivery fee may be waived depending on what the **State **is. We could write this using if…else if:

The preceding code will get bigger and harder to read the more states we add.

An alternative could be to use a switch statement to try and simplify this:

In the preceding code there is still a bit of “ceremony” with all the case blocks.

We could instead use a switch expression that makes use of property pattern matching:

?

Notice how the preceding code is a lot more succinct, and it’s easy to see all the cases and combinations.

What if for some States, the VIP status was not relevant for calculating delivery cost?

Suppose that the state “QE” always had a high delivery cost that never got reduced even for VIPs:

In the preceding code, if the State is “QE” then the delivery cost will be 99.99. Also notice the use of the discard _ that says “for all other combinations not listed above set the delivery cost to 5”.

#new features #icymi c# 8 #c# 8

 ICYMI C# 8 New Features: Simplify If Statements with Property Pattern Matching
1.05 GEEK