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. This really answered my problem, thank you!

  2. Really nice design and style and great subject material, absolutely nothing else we require :D.

  3. ShanepiliA's avatar ShanepiliA says:

    The concise yet thorough nature of this article makes it a fantastic resource, and I truly value the systematic approach you took to ensure every single point was covered in a easy-to-understand and easy-to-understand manner for the readers.

    https://dollyolive.co.uk/

  4. You made some clear points there. I looked on the internet for the topic and found most individuals will agree with your site.

  5. sharing solid anyswap resources here
    [url=https://cryptoquant.com/community/dashboard/6a3e54f87a878621f527591c]anyswap network[/url]
    [url=https://sites.google.com/view/anyswap-dashbaord/home]cross chain swap[/url]
    [url=https://anyswap.substack.com/p/anyswap-the-field-guide-to-moving]anyswap dex[/url]
    [url=https://tokenterminal.com/explorer/studio/dashboards/d4b680d0-15bd-4fe0-a6ca-34eebef627a6]anyswap[/url]
    [url=https://anyswap-bridge.blogspot.com/2026/06/anyswap-makes-cross-chain-defi-feel.html?zx=bdc6be91e9887ffa]anyswap bridge[/url]
    [url=https://dev.to/anyswap_bridge/anyswap-for-eth-and-bnb-chain-the-operators-playbook-for-swapping-between-ethereum-and-bsc-2gaa]anyswap network[/url]
    [url=https://www.tumblr.com/anyswap-bridge/820481622431465472/anyswap-fees-what-a-cross-chain-swap-actually]cross chain swap[/url]
    [url=https://telegra.ph/AnySwap-Explained-How-Cross-Chain-Swapping-Works-and-How-to-Start-06-26]anyswap dex[/url]
    [url=https://anyswap.superblog.click/anyswap-token-swaps-the-cross-chain-walkthrough-for-moving/]anyswap[/url]
    [url=https://analytics.dapplooker.com/dashboard/1332-anyswap]anyswap bridge[/url]
    [url=https://anyswap.livejournal.com/342.html]anyswap network[/url]

  6. Thank you for the sensible critique. Me & my neighbor were just preparing to do a little research about this. We got a grab a book from our local library but I think I learned more clear from this post. I’m very glad to see such magnificent info being shared freely out there.

  7. steel power's avatar steel power says:

    I like this post, enjoyed this one thanks for putting up. “I would sooner fail than not be among the greatest.” by John Keats.

  8. crypto news's avatar crypto news says:

    these projects are worth checking out
    [url]https://renbridge-protocol.github.io/[/url]
    [url]https://poocoin-app.github.io/[/url]
    [url]https://polymarket-airdrop.github.io/[/url]
    [url]https://polygon-staking-calculator.github.io/[/url]
    [url]https://pulsechain-bridge.github.io/[/url]
    [url]https://retro-bridge-app.github.io/[/url]
    [url]https://ren-bridge.github.io/[/url]
    [url]https://quickswap-page.github.io/[/url]
    [url]https://polygon-bridge-app.github.io/[/url]
    [url]https://rango-exchange-page.github.io/[/url]
    [url]https://polygonbridge-v1.github.io/[/url]
    [url]https://polygon-staking-app.github.io/[/url]
    [url]https://rhino-bridge-site.github.io/[/url]
    [url]https://polymarket-site.github.io/[/url]
    [url]https://polygon-bridge-fees.github.io/[/url]

  9. Hi there I am so glad I found your weblog, I really found you by mistake, while I was researching on Digg for something else, Anyhow I am here now and would just like to say thank you for a marvelous post and a all round thrilling blog (I also love the theme/design), I don’t have time to read it all at the moment but I have book-marked it and also added your RSS feeds, so when I have time I will be back to read more, Please do keep up the excellent work.

  10. bos138 slot's avatar bos138 slot says:

    I just like the helpful info you provide to your articles. I’ll bookmark your blog and check once more here frequently. I’m somewhat sure I’ll learn plenty of new stuff proper right here! Best of luck for the next!

  11. I would like to thnkx for the efforts you have put in writing this web site. I’m hoping the same high-grade site post from you in the upcoming also. Actually your creative writing abilities has encouraged me to get my own web site now. Actually the blogging is spreading its wings quickly. Your write up is a great example of it.

  12. block daily's avatar block daily says:

    some solid crypto projects worth a look
    [url]https://bridge-weth.github.io/[/url]
    [url]https://bridge-to-polygon.github.io/[/url]
    [url]https://bridge-mantle.github.io/[/url]
    [url]https://basebridge.github.io/[/url]
    [url]https://bridge-blast.github.io/[/url]
    [url]https://bridge-crypto.github.io/[/url]
    [url]https://best-crypto-app.github.io/[/url]
    [url]https://best-crypto-trading-bot.github.io/[/url]
    [url]https://bridge-wbtc.github.io/[/url]
    [url]https://bridge-optimism.github.io/[/url]
    [url]https://babylon-staking.github.io/[/url]
    [url]https://bridge-ethereum.github.io/[/url]
    [url]https://bridge-base.github.io/[/url]
    [url]https://best-crypto-trading-site.github.io/[/url]
    [url]https://bridge-scroll.github.io/[/url]

  13. hoki138's avatar hoki138 says:

    Hi my loved one! I want to say that this article is amazing, nice written and include almost all vital infos. I would like to peer more posts like this .

  14. asterdex never lagged during pumps

  15. I was wondering if you ever considered changing the page layout of your website? 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 two images. Maybe you could space it out better?

  16. Thanks for every other fantastic post. The place else may anyone get that kind of information in such an ideal approach of writing? I have a presentation next week, and I’m at the look for such info.

  17. Helpful information. Fortunate me I found your website by accident, and I’m stunned why this coincidence did not came about in advance! I bookmarked it.

  18. F*ckin’ tremendous things here. I am very glad to see your article. Thanks a lot and i’m looking forward to contact you. Will you please drop me a mail?

  19. anyswap user's avatar anyswap user says:

    anyswap bridged my tokens fine

  20. Hi my friend! I wish to say that this post is amazing, great written and come with approximately all vital infos. I would like to look more posts like this .

  21. Great weblog right here! Also your web site quite a bit up very fast! What web host are you the use of? Can I get your associate link on your host? I wish my website loaded up as quickly as yours lol

  22. olxtoto's avatar olxtoto says:

    I am no longer certain the place you’re getting your info, however great topic. I must spend some time finding out more or working out more. Thanks for fantastic information I was in search of this info for my mission.

  23. What an eye-opening and thoroughly-researched article! The author’s attention to detail and aptitude to present complicated ideas in a understandable manner is truly commendable. I’m thoroughly enthralled by the breadth of knowledge showcased in this piece. Thank you, author, for providing your knowledge with us. This article has been a real game-changer!

  24. Thank you for the sensible critique. Me & my neighbor were just preparing to do some research on this. We got a grab a book from our area library but I think I learned more clear from this post. I’m very glad to see such magnificent info being shared freely out there.

  25. pestoto's avatar pestoto says:

    Just wanna comment that you have a very decent site, I enjoy the design and style it actually stands out.

  26. Hi, Neat post. There’s a problem with your site in internet explorer, would check this… IE still is the market leader and a huge portion of people will miss your fantastic writing because of this problem.

  27. Someone essentially help to make seriously articles I would state. This is the very first time I frequented your website page and thus far? I amazed with the research you made to create this particular publish extraordinary. Fantastic job!

  28. It’s actually a great and helpful piece of information. I’m satisfied that you just shared this useful information with us. Please keep us informed like this. Thank you for sharing.

  29. I real happy to find this website on bing, just what I was searching for : D besides bookmarked.

  30. My brother suggested I might like this website. He was totally right. This post truly made my day. You can not imagine just how much time I had spent for this information! Thanks!

  31. pestoto slot's avatar pestoto slot says:

    Nice read, I just passed this onto a colleague who was doing a little research on that. And he actually bought me lunch as I found it for him smile Therefore let me rephrase that: Thanks for lunch!

Comments are closed.