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. clipp pro's avatar clipp pro says:

    Have you ever thought about including a little bit more than just your articles? I mean, what you say is fundamental and all. However think about if you added some great graphics or video clips to give your posts more, “pop”! Your content is excellent but with images and clips, this blog could certainly be one of the best in its niche. Superb blog!

  2. Woah! I’m really loving the template/theme of this site. It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between usability and appearance. I must say you’ve done a superb job with this. In addition, the blog loads extremely quick for me on Safari. Outstanding Blog!

  3. Veja como revisar TCC nas normas ABNT com checklist prático de estrutura, capa, sumário, citações e referências antes da entrega.

  4. You have observed very interesting points! ps nice web site.

  5. Thank you, I have just been looking for info about this subject for ages and yours is the best I have came upon till now. However, what concerning the conclusion? Are you positive about the source?

  6. dewi11's avatar dewi11 says:

    Thanks for any other informative site. Where else may I get that kind of information written in such an ideal manner? I’ve a project that I am simply now running on, and I’ve been on the look out for such information.

  7. Delta 8 THC's avatar Delta 8 THC says:

    I think you have remarked some very interesting details, thankyou for the post.

  8. dwg288's avatar dwg288 says:

    I reckon something truly special in this site.

  9. dwg288's avatar dwg288 says:

    I’ve recently started a website, the info you provide on this site has helped me greatly. Thank you for all of your time & work.

  10. Thankyou for helping out, great information.

  11. dewi11's avatar dewi11 says:

    There is obviously a lot to know about this. I assume you made various good points in features also.

  12. I know this if off topic but I’m looking into starting my own weblog and was curious what all is needed to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web smart so I’m not 100 positive. Any tips or advice would be greatly appreciated. Thank you

  13. I do agree with all of the ideas you’ve presented in your post. They’re very convincing and will definitely work. Still, the posts are too short for beginners. Could you please extend them a little from next time? Thanks for the post.

  14. seoflowpro – Color palette felt calming, nothing distracting, just focused, thoughtful design.

  15. dewi11's avatar dewi11 says:

    Thanks a lot for giving everyone an extraordinarily spectacular possiblity to read in detail from this web site. It can be very cool and jam-packed with a good time for me and my office acquaintances to visit your web site particularly three times a week to see the latest secrets you will have. And indeed, I’m so actually amazed for the incredible principles you serve. Some 4 areas in this post are particularly the most efficient we’ve ever had.

  16. optimizewizard – Content reads clearly, helpful examples made concepts easy to grasp.

  17. searchgenius – Pages loaded fast, images appeared sharp, and formatting stayed consistent.

  18. I regard something truly special in this web site.

  19. dewihoki's avatar dewihoki says:

    I loved as much as you’ll receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get bought an edginess over that you wish be delivering the following. unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this increase.

  20. dewi288's avatar dewi288 says:

    It’s really a nice and helpful piece of info. I’m glad that you shared this helpful information with us. Please keep us up to date like this. Thanks for sharing.

  21. dewi11's avatar dewi11 says:

    I like this site so much, bookmarked.

  22. dewihoki's avatar dewihoki says:

    I likewise conceive thence, perfectly written post! .

  23. Meggan Gliem's avatar Meggan Gliem says:

    seoshelf – Pages loaded fast, images appeared sharp, and formatting stayed consistent.

  24. rankboostai – Navigation felt smooth, found everything quickly without any confusing steps.

  25. dewi11's avatar dewi11 says:

    Hi, Neat post. There is an issue along with your site in internet explorer, might test this… IE nonetheless is the marketplace leader and a large section of folks will miss your wonderful writing due to this problem.

  26. leadstore – Found practical insights today; sharing this article with colleagues later.

  27. metricmarket – Content reads clearly, helpful examples made concepts easy to grasp.

  28. strategystore – Color palette felt calming, nothing distracting, just focused, thoughtful design.

  29. dewi11's avatar dewi11 says:

    Excellent items from you, man. I’ve have in mind your stuff previous to and you’re simply too great. I really like what you have acquired here, really like what you are saying and the way in which by which you are saying it. You’re making it entertaining and you continue to take care of to keep it sensible. I can not wait to learn much more from you. This is actually a great website.

  30. poros77's avatar poros77 says:

    Im no longer positive the place you are getting your info, however good topic. I needs to spend a while studying much more or working out more. Thanks for magnificent info I was searching for this info for my mission.

  31. ultra33's avatar ultra33 says:

    Hello just wanted to give you a quick heads up and let you know a few of the pictures aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome.

  32. poros77's avatar poros77 says:

    This web site is really a walk-through for all of the info you wanted about this and didn’t know who to ask. Glimpse here, and you’ll definitely discover it.

  33. Tyree Bert's avatar Tyree Bert says:

    searchlogic – Color palette felt calming, nothing distracting, just focused, thoughtful design.

  34. keywordvault – Content reads clearly, helpful examples made concepts easy to grasp.

  35. campaigncart – Color palette felt calming, nothing distracting, just focused, thoughtful design.

  36. gopay303's avatar gopay303 says:

    What i don’t realize is actually how you are not really much more well-liked than you may be right now. You are so intelligent. You realize thus significantly relating to this subject, produced me personally consider it from numerous varied angles. Its like women and men aren’t fascinated unless it is one thing to accomplish with Lady gaga! Your own stuffs nice. Always maintain it up!

  37. Just wish to say your article is as surprising. The clarity on your put up is just great and that i can assume you are knowledgeable on this subject. Well along with your permission let me to seize your RSS feed to keep updated with approaching post. Thanks 1,000,000 and please carry on the gratifying work.

  38. Forrest Dorf's avatar Forrest Dorf says:

    rankifyer – Content reads clearly, helpful examples made concepts easy to grasp.

  39. keywordking – Bookmarked this immediately, planning to revisit for updates and inspiration.

  40. Hello there! This is my first visit to your blog! We are a collection of volunteers and starting a new project in a community in the same niche. Your blog provided us valuable information to work on. You have done a marvellous job!

  41. poros77's avatar poros77 says:

    I visited a lot of website but I conceive this one has got something special in it in it

  42. gopay303's avatar gopay303 says:

    I conceive this site has got very wonderful pent content material content.

  43. poros77's avatar poros77 says:

    What’s Happening i am new to this, I stumbled upon this I have found It absolutely helpful and it has aided me out loads. I hope to contribute & aid other users like its aided me. Great job.

  44. he blog was how do i say it… relevant, finally something that helped me. Thanks

  45. Wava Munsch's avatar Wava Munsch says:

    rankgenius – Pages loaded fast, images appeared sharp, and formatting stayed consistent.

  46. seomastery – Content reads clearly, helpful examples made concepts easy to grasp.

  47. Jayson Fecat's avatar Jayson Fecat says:

    trafficwizard – Found practical insights today; sharing this article with colleagues later.

  48. ダッチワイフ 薄いお腹と魅力的な口Z-onedoll151cm「ソフィア」by @ Sate私たちはあなたの最も愛されている人形を作ることができます。フランスのハウスキーパーアニメSexDoll

  49. I have to show my thanks to you just for rescuing me from this particular difficulty. Just after checking throughout the the web and meeting recommendations which were not pleasant, I figured my entire life was over. Existing devoid of the answers to the problems you’ve resolved by means of your posting is a critical case, and those that would have adversely damaged my career if I hadn’t discovered the website. Your good competence and kindness in playing with all the stuff was useful. I’m not sure what I would’ve done if I hadn’t encountered such a point like this. I’m able to at this moment look forward to my future. Thanks for your time very much for your expert and results-oriented help. I will not hesitate to suggest the sites to any person who will need counselling about this situation.

Comments are closed.