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. hello everyone, my backlink bot is system

  2. I enjoy looking at and I conceive this website got some really utilitarian stuff on it! .

  3. boothcool's avatar boothcool says:

    Hello there! This post could not be written any better! Reading through this post reminds me of my old room mate! He always kept talking about this. I will forward this post to him. Pretty sure he will have a good read. Thanks for sharing!

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

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

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

  7. synthlayer – Appreciate the typography choices; comfortable spacing improved my reading experience.

  8. nanostack – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.

  9. YourDoll JP 父と子が中国で7つのシリコンドレスを持ってきました

  10. Hey There. I found your blog using msn. This is an extremely well written article. I will be sure to bookmark it and come back to read more of your useful information. Thanks for the post. I will definitely comeback.

  11. slotroyal188's avatar slotroyal188 says:

    Somebody necessarily help to make severely articles I’d state. This is the very first time I frequented your web page and to this point? I surprised with the analysis you made to create this actual submit extraordinary. Fantastic process!

  12. rtp royal188's avatar rtp royal188 says:

    I dugg some of you post as I cogitated they were invaluable invaluable

  13. Youre so cool! I dont suppose Ive learn something like this before. So nice to find somebody with some unique ideas on this subject. realy thank you for beginning this up. this web site is something that is wanted on the internet, someone with somewhat originality. helpful job for bringing one thing new to the web!

  14. As a Newbie, I am permanently browsing online for articles that can help me. Thank you

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

  16. IsmaelNiz's avatar IsmaelNiz says:

    Thanks for the auspicious writeup. It in truth was once a entertainment account it. Look complex to more introduced agreeable from you! However, how could we be in contact?
    tada gaming slots

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

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

  19. binaryforge – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.

  20. Yay google is my world beater assisted me to find this great web site! .

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

  22. toto macau's avatar toto macau says:

    I was curious if you ever thought of changing the structure of your site? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or 2 pictures. Maybe you could space it out better?

  23. I discovered your blog site on google and check a few of your early posts. Continue to keep up the very good operate. I just additional up your RSS feed to my MSN News Reader. Seeking forward to reading more from you later on!…

  24. Great post, I believe website owners should acquire a lot from this web site its very user genial.

  25. Greetings from Colorado! I’m bored to tears at work so I decided to browse your website on my iphone during lunch break. I love the information you provide here and can’t wait to take a look when I get home. I’m amazed at how quick your blog loaded on my mobile .. I’m not even using WIFI, just 3G .. Anyways, excellent blog!

  26. Hey, you used to write excellent, but the last few posts have been kinda boring… I miss your great writings. Past few posts are just a little bit out of track! come on!

  27. Great blog! I am loving it!! Will come back again. I am bookmarking your feeds also.

  28. You are my inspiration , I own few web logs and very sporadically run out from to post .

  29. Definitely consider that that you said. Your favorite justification seemed to be on the net the easiest factor to take into accout of. I say to you, I definitely get irked at the same time as people think about worries that they just do not recognize about. You managed to hit the nail upon the top and outlined out the entire thing without having side effect , folks could take a signal. Will probably be again to get more. Thank you

  30. I truly appreciate your piece of work, Great post.

  31. leadstore – Appreciate the typography choices; comfortable spacing improved my reading experience.

  32. strategystore – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.

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

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

  35. Phil Pawlik's avatar Phil Pawlik says:

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

  36. bro138's avatar bro138 says:

    Thankyou for helping out, great information.

  37. Very great post. I simply stumbled upon your weblog and wanted to say that I’ve really enjoyed browsing your weblog posts. In any case I’ll be subscribing on your feed and I hope you write once more soon!

  38. Hi there, i read your blog from time to time and i own a similar one and i was just wondering if you get a lot of spam feedback? If so how do you stop it, any plugin or anything you can advise? I get so much lately it’s driving me crazy so any help is very much appreciated.

  39. poros77's avatar poros77 says:

    naturally like your web-site but you have to take a look at the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to tell the truth then again I will definitely come again again.

  40. poros77's avatar poros77 says:

    Hey There. I found your blog using msn. This is an extremely well written article. I’ll be sure to bookmark it and come back to read more of your useful information. Thanks for the post. I will definitely return.

  41. I enjoy the efforts you have put in this, regards for all the great blog posts.

  42. That is really interesting, You’re a very skilled blogger. I’ve joined your feed and sit up for searching for extra of your wonderful post. Also, I’ve shared your site in my social networks!

  43. Rickie Isome's avatar Rickie Isome says:

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

  44. smarttrafficai – Appreciate the typography choices; comfortable spacing improved my reading experience.

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

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

  47. Devon Fawley's avatar Devon Fawley says:

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

  48. Dead composed articles, regards for information. “Life is God’s novel. Let him write it.” by Isaac Bashevis Singer.

  49. dewi11's avatar dewi11 says:

    I’ve learn some good stuff here. Certainly worth bookmarking for revisiting. I wonder how much effort you put to create such a great informative website.

  50. dewi11's avatar dewi11 says:

    Hi there! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!

Comments are closed.