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

    I enjoyed reading what you had to say.

  2. olxtoto's avatar olxtoto says:

    After I originally commented I clicked the -Notify me when new comments are added- checkbox and now every time a remark is added I get four emails with the identical comment. Is there any method you possibly can take away me from that service? Thanks!

  3. olxtoto link's avatar olxtoto link says:

    Only a smiling visitant here to share the love (:, btw outstanding design and style.

  4. What i don’t realize is actually how you’re not really much more well-liked than you might be right now. You are very intelligent. You realize therefore considerably relating to this subject, made me personally consider it from a lot of varied angles. Its like women and men aren’t fascinated unless it’s one thing to accomplish with Lady gaga! Your own stuffs outstanding. Always maintain it up!

  5. Very great post. I simply stumbled upon your blog and wished to mention that I have truly enjoyed surfing around your weblog posts. After all I will be subscribing to your feed and I hope you write again very soon!

  6. donkey punch's avatar donkey punch says:

    After I read this I screamed at the ceiling and my eyeballs blew up ! I really like your article. You’ve made my day! Thx again. Great post!

  7. 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!…

  8. I have been browsing online more than three hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. In my view, if all website owners and bloggers made good content as you did, the net will be much more useful than ever before.

  9. Hiya very nice blog!! Guy .. Excellent .. Amazing .. I’ll bookmark your blog and take the feeds additionally?KI’m satisfied to find so many useful info right here in the post, we want work out extra techniques on this regard, thank you for sharing. . . . . .

  10. Stephenviaps's avatar Stephenviaps says:

    Right now it sounds like Expression Engine is the preferred blogging platform out there right now. (from what I’ve read) Is that what you’re using on your blog?
    บาคาร่า

  11. Greetings! Quick question that’s completely off topic. Do you know how to make your site mobile friendly? My web site looks weird when viewing from my apple iphone. I’m trying to find a theme or plugin that might be able to correct this issue. If you have any suggestions, please share. With thanks!

  12. I will right away grab your rss as I can’t find your e-mail subscription link or newsletter service. Do you have any? Please allow me recognize in order that I may subscribe. Thanks.

  13. Have you ever thought about publishing an ebook or guest authoring on other blogs? I have a blog based upon on the same topics you discuss and would really like to have you share some stories/information. I know my subscribers would value your work. If you are even remotely interested, feel free to send me an e mail.

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

  15. abc.bet's avatar abc.bet says:

    Hello there! This is kind of off topic but I need some guidance from an established blog. Is it hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about setting up my own but I’m not sure where to begin. Do you have any tips or suggestions? Appreciate it

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

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

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

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

  20. VitaGLP Avis's avatar VitaGLP Avis says:

    You actually make it seem so easy with your presentation but I find this matter to be really something which I think I would never understand. It seems too complex and very broad for me. I’m looking forward for your next post, I will try to get the hang of it!

  21. da moz seo's avatar da moz seo says:

    Hi, 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 comments? If so how do you protect against it, any plugin or anything you can recommend? I get so much lately it’s driving me insane so any support is very much appreciated.

  22. hoki365 slot's avatar hoki365 slot says:

    I like this web site because so much useful material on here :D.

  23. usahampo's avatar usahampo says:

    You could definitely see your enthusiasm in the work you write. The world hopes for even more passionate writers such as you who aren’t afraid to mention how they believe. Always go after your heart.

  24. usahampo's avatar usahampo says:

    Hey there! I know this is somewhat off topic but I was wondering which blog platform are you using for this site? I’m getting tired of WordPress because I’ve had issues with hackers and I’m looking at alternatives for another platform. I would be great if you could point me in the direction of a good platform.

  25. usahampo's avatar usahampo says:

    Definitely believe that which you stated. Your favorite justification appeared to be on the net the easiest thing to be aware of. I say to you, I definitely get irked while people consider worries that they plainly don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people can take a signal. Will likely be back to get more. Thanks

  26. GARASISLOT's avatar GARASISLOT says:

    I used to be suggested this web site by way of my cousin. I am not certain whether this put up is written through him as no one else recognize such specified about my problem. You’re wonderful! Thank you!

  27. lgopro99's avatar lgopro99 says:

    I’d forever want to be update on new articles on this web site, saved to my bookmarks! .

  28. Absolutely written articles, appreciate it for entropy.

  29. neuro salt's avatar neuro salt says:

    Hi there, I found your web site via Google while looking for a related topic, your website came up, it looks good. I’ve bookmarked it in my google bookmarks.

  30. jelly tide's avatar jelly tide says:

    I’ve read several excellent stuff here. Certainly value bookmarking for revisiting. I wonder how a lot attempt you put to make this type of fantastic informative website.

  31. Hey this is kinda of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding experience so I wanted to get guidance from someone with experience. Any help would be enormously appreciated!

  32. I’m usually to blogging and i really appreciate your content. The article has actually peaks my interest. I am going to bookmark your website and keep checking for brand spanking new information.

  33. That is very fascinating, You are an overly professional blogger. I have joined your feed and sit up for seeking extra of your magnificent post. Also, I’ve shared your site in my social networks!

  34. audileaf's avatar audileaf says:

    I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz reply as I’m looking to design my own blog and would like to know where u got this from. thank you

  35. Honestly, I ended up going through most of it, which I don’t see often online. this was worth the time.

  36. Thank you a bunch for sharing this with all of us you really know what you are talking about! Bookmarked. Kindly additionally consult with my site =). We can have a link change contract between us!

  37. As I website possessor I conceive the content here is really fantastic, thankyou for your efforts.

  38. Hey, I think your site might be having browser compatibility issues. When I look at your website in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, very good blog!

  39. litoto login's avatar litoto login says:

    I think this website contains some rattling great info for everyone :D.

  40. tonic greens's avatar tonic greens says:

    But a smiling visitant here to share the love (:, btw great style. “Reading well is one of the great pleasures that solitude can afford you.” by Harold Bloom.

  41. Hey very nice blog!! Man .. Excellent .. Amazing .. I’ll bookmark your website and take the feeds also…I’m happy to find numerous useful information here in the post, we need develop more techniques in this regard, thanks for sharing. . . . . .

  42. Some truly interesting information, well written and loosely user friendly.

  43. We absolutely love your blog and find most of your post’s to be just what I’m looking for. Does one offer guest writers to write content for yourself? I wouldn’t mind publishing a post or elaborating on a lot of the subjects you write related to here. Again, awesome website!

  44. After study a few of the blog posts on your website now, and I truly like your way of blogging. I bookmarked it to my bookmark website list and will be checking back soon. Pls check out my web site as well and let me know what you think.

  45. This is actually interesting, I was able to follow along easily. definitely something worth bookmarking.

  46. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why waste your intelligence on just posting videos to your weblog when you could be giving us something enlightening to read?

Comments are closed.