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 am glad to be a visitant of this stark web blog! , regards for this rare info ! .
Hello my friend! I wish to say that this article is awesome, nice written and include approximately all significant infos. I would like to see more posts like this.
Some times its a pain in the ass to read what blog owners wrote but this internet site is rattling user genial! .
Regards for all your efforts that you have put in this. very interesting info .
You got a very good website, Gladiola I noticed it through yahoo.
You have mentioned very interesting points! ps decent web site.
I would like to thnkx for the efforts you have put in writing this blog. I am hoping the same high-grade blog post from you in the upcoming as well. In fact your creative writing abilities has inspired me to get my own blog now. Really the blogging is spreading its wings quickly. Your write up is a good example of it.
Hello, Neat post. There’s an issue with your web site in internet explorer, might check this… IE still is the market chief and a large section of other folks will omit your great writing because of this problem.
I love your blog.. very nice colors & theme. Did you create this website yourself? Plz reply back as I’m looking to create my own blog and would like to know wheere u got this from. thanks
you have a great blog here! would you like to make some invite posts on my blog?
I was reading through some of your articles on this site and I conceive this web site is very instructive! Keep on posting.
I love your blog.. very nice colors & theme. Did you create this website yourself? Plz reply back as I’m looking to create my own blog and would like to know wheere u got this from. thanks
I’m still learning from you, as I’m improving myself. I absolutely love reading all that is posted on your site.Keep the information coming. I enjoyed it!
Its fantastic as your other content : D, thankyou for posting. “In the spider-web of facts, many a truth is strangled.” by Paul Eldridge.
Hi my friend! I wish to say that this post is amazing, nice written and include approximately all vital infos. I would like to see more posts like this.
Appreciate it for this post, I am a big big fan of this internet site would like to go on updated.
An interesting discussion is worth comment. I think that you should write more on this topic, it might not be a taboo subject but generally people are not enough to speak on such topics. To the next. Cheers
Nice post. I be taught something more difficult on completely different blogs everyday. It is going to all the time be stimulating to learn content from different writers and observe a little something from their store. I’d want to make use of some with the content material on my blog whether you don’t mind. Natually I’ll give you a link in your internet blog. Thanks for sharing.
I was curious if you ever thought of changing the structure of your blog? 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 images. Maybe you could space it out better?
Real nice design and fantastic written content, practically nothing else we want : D.
Very interesting details you have observed, thankyou for posting. “The unspoken word never does harm.” by Kossuth.
I like this web blog very much so much great information.
Enjoyed looking through this, very good stuff, regards. “Shared joys make a friend, not shared sufferings.” by Friedrich Wilhelm Nietzsche.
I real pleased to find this web site on bing, just what I was looking for : D as well saved to my bookmarks.
You completed a number of fine points there. I did a search on the subject and found nearly all people will consent with your blog.
My husband and i got excited that Louis managed to complete his preliminary research through your ideas he gained out of your site. It’s not at all simplistic just to possibly be giving freely guides which most people have been trying to sell. And we all recognize we now have the blog owner to thank for this. Those illustrations you have made, the easy site navigation, the friendships you will make it easier to instill – it is many wonderful, and it is facilitating our son and the family feel that that topic is pleasurable, and that is unbelievably serious. Many thanks for all!
I loved as much as you will receive carried out right here. The sketch is attractive, your authored subject matter stylish. nonetheless, you command get bought an nervousness over that you wish be delivering the following. unwell unquestionably come further formerly again since exactly the same nearly very often inside case you shield this hike.
Great post. I was checking constantly this blog and I’m impressed! Very helpful info specially the last part 🙂 I care for such info much. I was seeking this certain information for a long time. Thank you and good luck.
Currently it seems like Movable Type is the best blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?
It is in reality a great and helpful piece of info. I am satisfied that you simply shared this helpful information with us. Please stay us up to date like this. Thanks for sharing.
Hello there I am so grateful I found your website, I really found you by accident, while I was searching on Digg for something else, Anyhow I am here now and would just like to say many thanks for a tremendous post and a all round enjoyable blog (I also love the theme/design), I don’t have time to go through it all at the minute but I have bookmarked it and also added your RSS feeds, so when I have time I will be back to read more, Please do keep up the great work.
Great awesome issues here. I am very glad to see your article. Thank you so much and i’m having a look forward to contact you. Will you please drop me a e-mail?
Thank you so much for giving everyone an exceptionally marvellous possiblity to check tips from this web site. It is usually so superb and as well , packed with amusement for me personally and my office colleagues to search your site no less than three times in a week to learn the new items you have got. Of course, I’m usually pleased considering the special hints you serve. Some 4 facts in this post are surely the finest I have ever had.
What i don’t understood is actually how you’re not actually a lot more well-liked than you might be right now. You are so intelligent. You realize therefore significantly on the subject of this topic, made me individually believe it from so many various angles. Its like women and men aren’t fascinated until it’s one thing to do with Lady gaga! Your individual stuffs outstanding. Always care for it up!
Tired of Tinnitus or Hearing Problems? Here’s a Natural Solution That’s Changing Lives Are you constantly bothered by ringing in the ears (tinnitus), hearing difficulties, or sound clarity issues?
There is noticeably a bundle to know about this. I assume you made certain nice points in features also.
LottoChamp is a specialized lottery prediction software designed to give players a statistical edge. Instead of relying on luck or random numbers, the platform uses mathematical algorithms and historical draw data to help users make more strategic number selections.
Thank you for another informative web site. The place else may I am getting that type of info written in such a perfect method? I have a undertaking that I am just now operating on, and I’ve been on the look out for such information.
PROSTADINE is truly unlike anything you’ve ever encountered in your life. It stands as the sole droplet solution that incorporates nine potent natural ingredients, working in perfect synergy to safeguard the health and mineral balance of your prostate well into your golden years.
Hello, you used to write excellent, but the last few posts have been kinda boring?K I miss your great writings. Past few posts are just a little bit out of track! come on!
The ice water hack is a simple trick that involves using cold water to naturally activate your body’s thermogenic process. When you drink ice water, your body has to work harder to regulate its temperature, burning extra calories in the process.
Hello, Neat post. There is an issue together with your website in internet explorer, might test this?K IE still is the marketplace chief and a huge portion of people will leave out your fantastic writing because of this problem.
Great write-up, I?¦m normal visitor of one?¦s web site, maintain up the nice operate, and It’s going to be a regular visitor for a long time.
Many men who have tried the blue salt trick report increased stamina, better performance, and a renewed sense of confidence.
Wow, fantastic blog layout! How lengthy have you ever been blogging for? you made blogging look easy. The total glance of your website is magnificent, as smartly as the content material!
I dugg some of you post as I cogitated they were very helpful handy
This site is my inspiration , very great design and perfect subject material.
Sleep Lean is a natural nighttime weight management supplement designed to help you burn fat, improve sleep quality, and balance hormones—all while you rest.
Thanks for all your efforts that you have put in this. very interesting info .
Oh my goodness! a tremendous article dude. Thanks However I am experiencing concern with ur rss . Don’t know why Unable to subscribe to it. Is there anyone getting similar rss drawback? Anybody who is aware of kindly respond. Thnkx