Mastering C# – Pattern Matching

Microsoft has a wonderful tutorial on pattern matching, in which you model a lock (to raise or lower a ship when there would otherwise be a waterfall). They model the two doors and the water level.

While their example is excellent it is long, and in this blog post I’m going to take the essence of pattern matching using their example.

We start with a state machine:

The chart indicates whether the gate should be opened or closed based on the new setting and the current status of the gate as well as the water level. We read it as follows: if the new setting is closed, it doesn’t matter what the starting state of the gate is, nor the water level, we close the gate (first three lines).

On the other hand, if the gate is closed (line 4) and we give it a new state of open and the water level is high, then we open the gate. If, on line 5, we tell it to open from a closed state, but the water level is low then we have an error (don’t open when the water is low).

Finally, if we say open and it is open and the water level is high, then we do, in fact, open.

These states can be modeled in a switch expression using pattern matching where true = open and false = closed:

HighWaterGateOpen = (open, HighWaterGateOpen, CanalLockWaterLevel) switch
{
(false, false, WaterLevel.High) => false,
(false, false, WaterLevel.Low) => false,
(false, true, WaterLevel.High) => false,
(true, false, WaterLevel.High) => true,
(true, false, WaterLevel.Low) => throw new InvalidOperationException("Cannot open high gate when the water is low"),
(true, true, WaterLevel.High) => true,

As you can see, the first three arms of this expression start false and end false, as we saw above. Next, we have the case where the new state is true, the current state is false and the Water level is high. This causes the gate to open (true).

But it gets easier. First, we need the default case. In the latest C# an underscore matches anything. So we add

_ => throw new InvalidOperationException(“Invalid internal state”),

as the default, meaning if anything else comes up, it is invalid.

Note that, as we said, the first three arms all evaluate to false. We can replace them with
(false, _, _) => false,
You read this as, if the first value is false (the new condition) then no matter what the second and third conditions are, we will evaluate to false.

Next we need to know what to do if the new state is true. This is slightly tricker as it depends on the water level:

(true, _, WaterLevel.High) => true, 
(true, false, WaterLevel.Low) => throw new InvalidOperationException("Cannot open high gate when the water is low"), => throw new InvalidOperationException("Invalid internal state"),

Thus, if the new state is true, and the water level is high (no matter the state of the gate), then we do open the gate. If the new state is open (from on original state o closed) and the water level is low then, uh oh.

Here is the final version of the method:

// Change the upper gate.
public void SetHighGate(bool open)
{
    HighWaterGateOpen = (open, HighWaterGateOpen, CanalLockWaterLevel) switch
    {
        (false, _,    _)               => false,
        (true, _,     WaterLevel.High) => true,
        (true, false, WaterLevel.Low)  => throw new InvalidOperationException("Cannot open high gate when the water is low"),
        _                              => throw new InvalidOperationException("Invalid internal state"),
    };
}

All of this is simpler, cleaner and thus easier to understand and maintain than a series of if statements or even a set of switch statements.

Unknown's avatar

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. Liberty is a Senior AI Engineer at the University of Pittsburgh Medical Center, and was a Team Lead and Senior Software Engineer for various corporations, a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a 21 year Microsoft MVP.
This entry was posted in C# 12, Mini-Tutorial, Programming. Bookmark the permalink.

1,645 Responses to Mastering C# – Pattern Matching

  1. Plain-language intro on what is paraswap — DEX aggregator that splits orders across multiple liquidity venues — clean answer to what is paraswap in a single paragraph.

  2. Please let me know if you’re looking for a article author for your weblog. You have some really good articles and I feel I would be a good asset. If you ever want to take some of the load off, I’d love to write some content for your blog in exchange for a link back to mine. Please send me an e-mail if interested. Many thanks!

  3. paraswap api's avatar paraswap api says:

    Fee structure breakdown on paraswap fees — protocol fee tier, partner fee share, gas overhead, slippage realization — exactly the paraswap fees stack worth modeling before sizing trades.

  4. Fascinating blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog shine. Please let me know where you got your design. Thanks

  5. It’s actually a cool and useful piece of info. I am glad that you shared this useful info with us. Please stay us up to date like this. Thank you for sharing.

  6. It’s in point of fact a great and useful piece of information. I am glad that you shared this useful info with us. Please stay us informed like this. Thanks for sharing.

  7. Good write-up, I am normal visitor of one’s site, maintain up the nice operate, and It’s going to be a regular visitor for a lengthy time.

  8. I saw a lot of website but I believe this one contains something special in it in it

  9. Appreciate it for helping out, fantastic info. “I have witnessed the softening of the hardest of hearts by a simple smile.” by Goldie Hawn.

  10. renbridge's avatar renbridge says:

    DeFi yield routes on renbridge defi — Curve renBTC pool, Yearn vaults, Convex incentives — practical yield destinations for renbridge users.

  11. renBTC's avatar renBTC says:

    renBTC mechanics on renBTC — 1:1 backing, mint and burn flow, liquidity on Curve and Sushi — the renBTC story that makes renbridge useful for DeFi composability.

  12. gelatide's avatar gelatide says:

    Yay google is my king assisted me to find this outstanding web site! .

  13. Regards for helping out, excellent information.

  14. join today's avatar join today says:

    Some nice points there.

  15. OLanepiliA's avatar OLanepiliA says:

    The tone of this post feels calm and balanced, helping the discussion stay easy and approachable.

    купить inmode Forma V

  16. nomiswap's avatar nomiswap says:

    Fee breakdown on nomiswap — swap fee, LP share, protocol cut, gas on BSC — exactly the nomiswap numbers worth checking before sizing trades.

  17. nomiswap dex's avatar nomiswap dex says:

    BSC wallet setup on nomiswap guide — add BNB Chain network, fund BNB for gas, connect via WalletConnect — beginner-friendly nomiswap onboarding for first-time BSC users.

  18. Hi there, just became aware of your blog through Google, and found that it’s truly informative. I am gonna watch out for brussels. I will be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers!

  19. Can I just say what a relief to find someone who actually knows what theyre talking about on the internet. You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I cant believe youre not more popular because you definitely have the gift.

  20. Great article and right to the point. I am not sure if this is truly the best place to ask but do you folks have any thoughts on where to hire some professional writers? Thank you 🙂

  21. Hi there! I just would like to give a huge thumbs up for the good data you have got right here on this post. I will likely be coming again to your blog for extra soon.

  22. so much wonderful info on here, :D.

  23. fast service's avatar fast service says:

    Interesting content. I truly appreciate this post. I’m going to like your blog on Tumblr. You appear to know a lot about this. The people at Chicken fancier are a bunch of scumbags. I enjoyed reading this. I truly appreciate this post. I’m going to like your blog on Pinterest. You’ve made my day! Thx again. I really like your article. Nice write up. Your article has proven useful to me. It’s like you wrote the book on it or something. I enjoyed your post. Thank you. Nice write up. Good job on this article! Awesome points, totally what I needed.

  24. Thanks for this wonderful post, I am glad I detected this website on yahoo.

  25. Have you ever thought about adding a little bit more than just your articles? I mean, what you say is important and everything. But just imagine if you added some great images or video clips to give your posts more, “pop”! Your content is excellent but with pics and clips, this site could definitely be one of the very best in its niche. Amazing blog!

  26. Really excellent info can be found on web site.

  27. Thanks for sharing superb informations. Your web-site is so cool. I’m impressed by the details that you’ve on this site. It reveals how nicely you perceive this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found just the info I already searched everywhere and just could not come across. What a great website.

  28. You appear to know a lot about this. I have been looking everywhere for this! Nice read.{ I truly appreciate this post. | Thumbs up!| I have been telling people exactly the same thing for years.

  29. ShanepiliA's avatar ShanepiliA says:

    The overall tone of this post feels very balanced and approachable, because it keeps the conversation enjoyable and informative without making the subject feel too heavy for the average reader online.

    no deposit bonus

  30. 377bet's avatar 377bet says:

    It’s hard to find knowledgeable people on this topic, but you sound like you know what you’re talking about! Thanks

  31. Normally I do not read article on blogs, but I wish to say that this write-up very forced me to try and do so! Your writing style has been amazed me. Thanks, quite nice article.

  32. slot online's avatar slot online says:

    An interesting dialogue is price comment. I think that it is best to write extra on this matter, it may not be a taboo topic however typically individuals are not enough to speak on such topics. To the next. Cheers

  33. Thank you for another informative blog. Where else could I get that kind of information written in such an ideal way? I have a project that I’m just now working on, and I have been on the look out for such info.

  34. forced anal's avatar forced anal says:

    Thanks for posting this up on your website. Nice read. You’ve made my day! Thx again. I truly appreciate this post. Act now. Great read. Interesting content. Your article has proven useful to me. I really like your article. Thanks for putting this up on your website. Good job on this article! This is an excellent, an eye-opener for sure! You appear to know a lot about this. Hit me up! Great read. I truly appreciate this post. There is something about your website that is rather alluring and I’d like to know just what it could be.

  35. Hey! I just would like to give a huge thumbs up for the great info you’ve got here on this post. I will be coming again to your blog for more soon.

  36. You have brought up a very excellent details , thankyou for the post.

  37. situs mpo100's avatar situs mpo100 says:

    I am glad to be one of the visitors on this outstanding site (:, thankyou for posting.

  38. Enjoyed reading this, very good stuff, thankyou. “Be not careless in deeds, nor confused in words, nor rambling in thought.” by Marcus Aurelius Antoninus.

  39. I’ve been absent for a while, but now I remember why I used to love this website. Thanks , I’ll try and check back more often. How frequently you update your site?

  40. My husband and i have been really peaceful Emmanuel could complete his web research through your ideas he gained from your very own web site. It’s not at all simplistic to simply always be freely giving steps that many people could have been trying to sell. Therefore we recognize we have the website owner to give thanks to because of that. All the illustrations you have made, the simple web site menu, the friendships you will make it easier to create – it’s got all unbelievable, and it is aiding our son in addition to us imagine that the theme is thrilling, and that is pretty important. Thank you for the whole thing!

  41. Some genuinely interesting details you have written.Aided me a lot, just what I was searching for :D.

  42. senang4d's avatar senang4d says:

    When I originally commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Thanks!

  43. olxtoto asia's avatar olxtoto asia says:

    wonderful submit, very informative. I’m wondering why the other specialists of this sector do not realize this. You must continue your writing. I’m confident, you’ve a great readers’ base already!

  44. I precisely wanted to thank you very much yet again. I’m not certain the things I could possibly have gone through without the actual ways discussed by you concerning my area. It had become the horrifying difficulty in my circumstances, nevertheless taking note of the very specialised avenue you dealt with the issue made me to leap for fulfillment. I’m thankful for your service and as well , hope you know what a powerful job you are always getting into training many people with the aid of your web site. Most probably you’ve never encountered any of us.

  45. I have been browsing online greater than three hours as of late, yet I by no means found any interesting article like yours. It’s lovely price enough for me. In my view, if all web owners and bloggers made good content material as you did, the internet shall be a lot more helpful than ever before.

  46. I do trust all of the ideas you have offered on your post. They are really convincing and can definitely work. Nonetheless, the posts are too brief for starters. May you please prolong them a bit from subsequent time? Thank you for the post.

  47. Hmm it appears like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog blogger but I’m still new to the whole thing. Do you have any suggestions for first-time blog writers? I’d really appreciate it.

  48. prediksi sdy's avatar prediksi sdy says:

    I haven’t checked in here for a while because I thought it was getting boring, but the last several posts are great quality so I guess I’ll add you back to my everyday bloglist. You deserve it my friend 🙂

  49. olxtoto's avatar olxtoto says:

    Greetings! Very helpful advice on this article! It is the little changes that make the biggest changes. Thanks a lot for sharing!

Comments are closed.