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

    I like this weblog so much, saved to favorites.

  2. poros77's avatar poros77 says:

    Pretty! This was a really wonderful post. Thank you for your provided information.

  3. poros77's avatar poros77 says:

    I dugg some of you post as I cerebrated they were invaluable extremely helpful

  4. Nice post. I was checking constantly this blog and I am impressed! Very useful info specifically the last part 🙂 I care for such information much. I was seeking this particular information for a very long time. Thank you and best of luck.

  5. hitam138's avatar hitam138 says:

    I was more than happy to search out this net-site.I needed to thanks on your time for this glorious learn!! I undoubtedly enjoying each little bit of it and I’ve you bookmarked to check out new stuff you blog post.

  6. monas77's avatar monas77 says:

    This is the precise weblog for anybody who needs to search out out about this topic. You realize a lot its virtually laborious to argue with you (not that I really would want…HaHa). You definitely put a new spin on a subject thats been written about for years. Great stuff, just great!

  7. jagoledak's avatar jagoledak says:

    I’m not sure exactly why but this site is loading very slow for me. Is anyone else having this problem or is it a issue on my end? I’ll check back later on and see if the problem still exists.

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

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

  10. Huong Fyksen's avatar Huong Fyksen says:

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

  11. Dan Contreas's avatar Dan Contreas says:

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

  12. TOP 10 RICHEST – Mobile version looks perfect; no glitches, fast scrolling, crisp text.

  13. gopay303's avatar gopay303 says:

    I’m really enjoying the theme/design of your blog. Do you ever run into any browser compatibility issues? A few of my blog audience have complained about my blog not operating correctly in Explorer but looks great in Chrome. Do you have any solutions to help fix this issue?

  14. jagoledak's avatar jagoledak says:

    I have not checked in here for some time as I thought it was getting boring, but the last few posts are great quality so I guess I’ll add you back to my daily bloglist. You deserve it my friend 🙂

  15. monas77's avatar monas77 says:

    Sweet website , super pattern, very clean and utilise genial.

  16. gopay303's avatar gopay303 says:

    you’ve gotten a great blog here! would you wish to make some invite posts on my blog?

  17. monas77's avatar monas77 says:

    You made some decent factors there. I looked on the internet for the difficulty and located most individuals will associate with along with your website.

  18. seoworks – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.

  19. Elvin Konma's avatar Elvin Konma says:

    trafficforge – Mobile version looks perfect; no glitches, fast scrolling, crisp text.

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

  21. Bee Dear's avatar Bee Dear says:

    serpmaster – Loved the layout today; clean, simple, and genuinely user-friendly overall.

  22. rankmachines – Loved the layout today; clean, simple, and genuinely user-friendly overall.

  23. hitam138's avatar hitam138 says:

    I truly enjoy looking at on this site, it has fantastic blog posts. “The great secret of power is never to will to do more than you can accomplish.” by Henrik Ibsen.

  24. teslatoto's avatar teslatoto says:

    I am glad that I noticed this website, precisely the right information that I was looking for! .

  25. Kara Artz's avatar Kara Artz says:

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

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

  27. Devin Auther's avatar Devin Auther says:

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

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

  29. Mitch Lorge's avatar Mitch Lorge says:

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

  30. scam money's avatar scam money says:

    I truly enjoy looking through on this site, it has superb posts. “Wealth and children are the adornment of life.” by Koran.

  31. bro138's avatar bro138 says:

    I have been checking out a few of your posts and i can state clever stuff. I will definitely bookmark your website.

  32. luxury333's avatar luxury333 says:

    Very instructive and excellent body structure of subject material, now that’s user pleasant (:.

  33. Hiya, I am really glad I’ve found this info. Today bloggers publish just about gossips and web and this is actually annoying. A good web site with exciting content, this is what I need. Thank you for keeping this web-site, I will be visiting it. Do you do newsletters? Can’t find it.

  34. olxtoto's avatar olxtoto says:

    Hey there! Would you mind if I share your blog with my zynga group? There’s a lot of folks that I think would really enjoy your content. Please let me know. Thanks

  35. Fantastic blog you have here but I was wondering if you knew of any community forums that cover the same topics talked about here? I’d really love to be a part of community where I can get opinions from other experienced people that share the same interest. If you have any suggestions, please let me know. Bless you!

  36. LewisGor's avatar LewisGor says:

    Hello there I am so grateful I found your site, I really found you by accident, while I was searching on Yahoo for something else, Regardless I am here now and would just like to say kudos for a tremendous post and a all round exciting blog (I also love the theme/design), I don’t have time to read it all at the minute but I have saved it and also added in your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the superb work.
    https://share.google/nRNBxmpL8BcmMVULw

  37. doll forever's avatar doll forever says:

    ラブドール 通販 実際には、私たちが知っているように、セックス人形とその背後にある開発は本当に素晴らしいです、それらは確かにチェックする価値のあるものです。

  38. growthbots – Bookmarked this immediately, planning to revisit for updates and inspiration.

  39. Hobert Quon's avatar Hobert Quon says:

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

  40. funnelbot – Appreciate the typography choices; comfortable spacing improved my reading experience.

  41. seoaccelerator – Navigation felt smooth, found everything quickly without any confusing steps.

  42. clickautomation – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.

  43. Magnificent beat ! I wish to apprentice even as you amend your web site, how can i subscribe for a blog website? The account helped me a acceptable deal. I had been tiny bit familiar of this your broadcast offered vibrant transparent concept

  44. Jelly Lean's avatar Jelly Lean says:

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

  45. marketsprint – Loved the layout today; clean, simple, and genuinely user-friendly overall.

  46. Jody Lamblin's avatar Jody Lamblin says:

    rankhustle – Loved the layout today; clean, simple, and genuinely user-friendly overall.

  47. digitalpush – Navigation felt smooth, found everything quickly without any confusing steps.

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

  49. seocommand – Loved the layout today; clean, simple, and genuinely user-friendly overall.

  50. My brother recommended I might like this web site. He used to be totally right. This put up actually made my day. You can not consider simply how so much time I had spent for this information! Thanks!

Comments are closed.