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.






































I like this weblog so much, saved to favorites.
Pretty! This was a really wonderful post. Thank you for your provided information.
I dugg some of you post as I cerebrated they were invaluable extremely helpful
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.
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.
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!
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.
brandengine – Pages loaded fast, images appeared sharp, and formatting stayed consistent.
webstrategy – Pages loaded fast, images appeared sharp, and formatting stayed consistent.
marketexperts – Color palette felt calming, nothing distracting, just focused, thoughtful design.
conversionpro – Bookmarked this immediately, planning to revisit for updates and inspiration.
TOP 10 RICHEST – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
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?
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 🙂
Sweet website , super pattern, very clean and utilise genial.
you’ve gotten a great blog here! would you wish to make some invite posts on my blog?
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.
seoworks – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.
trafficforge – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
trafficpilot – Found practical insights today; sharing this article with colleagues later.
serpmaster – Loved the layout today; clean, simple, and genuinely user-friendly overall.
rankmachines – Loved the layout today; clean, simple, and genuinely user-friendly overall.
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.
I am glad that I noticed this website, precisely the right information that I was looking for! .
serpmaster – Color palette felt calming, nothing distracting, just focused, thoughtful design.
trafficpilot – Pages loaded fast, images appeared sharp, and formatting stayed consistent.
seoworks – Found practical insights today; sharing this article with colleagues later.
trafficforge – Content reads clearly, helpful examples made concepts easy to grasp.
rankmachines – Navigation felt smooth, found everything quickly without any confusing steps.
I truly enjoy looking through on this site, it has superb posts. “Wealth and children are the adornment of life.” by Koran.
I have been checking out a few of your posts and i can state clever stuff. I will definitely bookmark your website.
Very instructive and excellent body structure of subject material, now that’s user pleasant (:.
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.
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
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!
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
ラブドール 通販 実際には、私たちが知っているように、セックス人形とその背後にある開発は本当に素晴らしいです、それらは確かにチェックする価値のあるものです。
growthbots – Bookmarked this immediately, planning to revisit for updates and inspiration.
marketautomate – Color palette felt calming, nothing distracting, just focused, thoughtful design.
funnelbot – Appreciate the typography choices; comfortable spacing improved my reading experience.
seoaccelerator – Navigation felt smooth, found everything quickly without any confusing steps.
clickautomation – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.
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
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!
marketsprint – Loved the layout today; clean, simple, and genuinely user-friendly overall.
rankhustle – Loved the layout today; clean, simple, and genuinely user-friendly overall.
digitalpush – Navigation felt smooth, found everything quickly without any confusing steps.
autogrowth – Color palette felt calming, nothing distracting, just focused, thoughtful design.
seocommand – Loved the layout today; clean, simple, and genuinely user-friendly overall.
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!