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’ll immediately take hold of your rss feed as I can not to find your e-mail subscription link or e-newsletter service. Do you’ve any? Please let me recognise so that I may subscribe. Thanks.
hemoroid tedavisi
Hiya! Quick question that’s completely off topic. Do you know how to make your site mobile friendly? My site looks weird when viewing from my apple iphone. I’m trying to find a theme or plugin that might be able to fix this problem. If you have any recommendations, please share. Thanks!
keep coming back to eigenlayer restaking.
friends recommended anyswap here
gelatin horse trick recipe
I like the helpful information you supply in your articles. I’ll bookmark your weblog and take a look at again here frequently. I’m rather sure I will learn lots of new stuff right right here! Best of luck for the next!
Hey there! I’ve been following your web site for some time now and finally got the courage to go ahead and give you a shout out from Dallas Tx! Just wanted to mention keep up the fantastic job!
switched to anyswap last week.
I enjoy your writing style really loving this website .
I really appreciate your piece of work, Great post.
You can definitely see your expertise within the paintings you write. The arena hopes for more passionate writers like you who are not afraid to say how they believe. All the time follow your heart.
nice manta bridge
ankara web tasarım
Some genuinely interesting info , well written and generally user pleasant.
jellyfil
I’m not sure why but this web site is loading very slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later and see if the problem still exists.
Nice weblog right here! Additionally your web site loads up fast! What web host are you the use of? Can I get your affiliate link for your host? I desire my web site loaded up as fast as yours lol
This is very interesting, You’re an excessively professional blogger. I’ve joined your feed and sit up for searching for extra of your wonderful post. Also, I’ve shared your website in my social networks!
We’re a bunch of volunteers and starting a brand new scheme in our community. Your site offered us with helpful information to paintings on. You’ve performed a formidable job and our whole group might be grateful to you.
Good job on this article! You are a very persuasive writer. I enjoyed reading what you had to say. Nice read. Have you ever heard of Free access? Good job on this article! I have been looking everywhere for this! Your article has proven useful to me. Hit me up! I have been looking everywhere for this! This information is magnificent. You appear to know a lot about this. Interesting content. Good job on this article! I enjoyed reading what you had to say. Great read. I truly appreciate this post.
solid take on BTC ETF flows
Gelatin Horse Trick
Usually I don’t read article on blogs, but I wish to say that this write-up very forced me to try and do so! Your writing style has been amazed me. Thanks, quite nice article.
What i don’t realize is actually how you’re not actually much more well-preferred than you may be right now. You are very intelligent. You understand therefore significantly relating to this topic, made me in my view imagine it from so many various angles. Its like women and men don’t seem to be fascinated except it’s one thing to do with Lady gaga! Your personal stuffs nice. Always deal with it up!
I enjoy you because of every one of your work on this web site. My mother take interest in engaging in research and it’s simple to grasp why. All of us notice all relating to the compelling medium you convey insightful guides on this website and therefore inspire response from other individuals on the point and our child is in fact learning a lot. Enjoy the rest of the new year. You have been conducting a great job.
It’s like you wrote the book on it or something. Your article has proven useful to me. Good job on this article! Sorry to bug you, however we could have many more questions I’d like answers for. I have been happy with s8e8 s8e8. It’s like you wrote the book on it or something. Some nice points there. Nice read. You are obviously very knowledgeable. Thumbs up! Good job on this article! This is an excellent, an eye-opener for sure! Thanks for writing this. I enjoyed your post. Thank you. Thumbs up! I enjoyed reading this. You appear to know a lot about this.
Do you mind if I quote a few of your articles as long as I provide credit and sources back to your webpage? My blog is in the exact same niche as yours and my users would really benefit from a lot of the information you provide here. Please let me know if this ok with you. Thanks!
ostim seo
Hit me up!
Horse Gelatin Trick Recipe for Men
Hydrogen Peroxide for ed
Spot on with this write-up, I actually assume this website needs rather more consideration. I’ll most likely be once more to learn far more, thanks for that info.
You have remarked very interesting details! ps decent site. “I understand a fury in your words, But not the words.” by William Shakespeare.
hello there and thank you in your information – I’ve definitely picked up anything new from right here. I did on the other hand expertise some technical points the use of this web site, since I experienced to reload the website many occasions previous to I could get it to load correctly. I were brooding about in case your web host is OK? Not that I’m complaining, but sluggish loading instances instances will sometimes impact your placement in google and can injury your high-quality ranking if advertising and ***********|advertising|advertising|advertising and *********** with Adwords. Well I am adding this RSS to my email and could glance out for much extra of your respective fascinating content. Make sure you update this again soon..
hemoroid basur
It’s really a great and useful piece of information. I am satisfied that you shared this useful information with us. Please stay us informed like this. Thank you for sharing.
hi!,I love your writing very so much! proportion we keep up a correspondence more approximately your article on AOL? I require an expert in this space to solve my problem. May be that is you! Having a look forward to look you.
I’m really loving the theme/design of your website. Do you ever run into any web browser compatibility issues? A number of my blog audience have complained about my site not working correctly in Explorer but looks great in Firefox. Do you have any ideas to help fix this problem?
Nice blog here! Also your website loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my website loaded up as fast as yours lol
quick swap stablecoin guide
fast swap stable
Greetings from Idaho! I’m bored at work so I decided to check out your website on my iphone during lunch break. I really like the info you provide here and can’t wait to take a look when I get home. I’m surprised at how quick your blog loaded on my cell phone .. I’m not even using WIFI, just 3G .. Anyhow, good site!
hello there and thank you for your info – I’ve certainly picked up anything new from right here. I did however expertise a few technical points using this site, as I experienced to reload the site a lot of times previous to I could get it to load properly. I had been wondering if your hosting is OK? Not that I’m complaining, but slow loading instances times will sometimes affect your placement in google and could damage your high quality score if ads and marketing with Adwords. Anyway I am adding this RSS to my email and can look out for much more of your respective interesting content. Make sure you update this again very soon..
Good write-up, I am normal visitor of one’s website, maintain up the nice operate, and It is going to be a regular visitor for a long time.
Good info. Lucky me I reach on your website by accident, I bookmarked it.
Please write more! You’ve made my day! Thx again. It’s like you read my thoughts! Nice read.
Your style is so unique compared to many other people. Thank you for publishing when you have the opportunity,Guess I will just make this bookmarked.
easy stable coin swap
try swap stablecoin today