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. I couldn’t resist commenting

  2. Wonderful blog! Do you have any tips and hints for aspiring writers? I’m planning to start my own site soon but I’m a little lost on everything. Would you suggest starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely confused .. Any recommendations? Cheers!

  3. deposit 5000's avatar deposit 5000 says:

    Hey, you used to write fantastic, but the last few posts have been kinda boring… I miss your super writings. Past several posts are just a little out of track! come on!

  4. I really enjoy examining on this web site, it has got excellent posts. “One should die proudly when it is no longer possible to live proudly.” by Friedrich Wilhelm Nietzsche.

  5. Precisely what I was looking for, thanks for putting up.

  6. Some genuinely wonderful articles on this site, thank you for contribution. “The difference between fiction and reality Fiction has to make sense.” by Tom Clancy.

  7. Regards for this post, I am a big fan of this website would like to go on updated.

  8. I’m not that much of a online reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your website to come back later on. All the best

  9. You really make it appear really easy with your presentation but I find this matter to be actually one thing which I believe I would never understand. It seems too complicated and very vast for me. I am having a look forward on your subsequent submit, I will attempt to get the dangle of it!

  10. gelatide's avatar gelatide says:

    Wonderful website you have here but I was curious about if you knew of any community forums that cover the same topics talked about in this article? I’d really like to be a part of community where I can get feed-back from other knowledgeable people that share the same interest. If you have any recommendations, please let me know. Appreciate it!

  11. hey there and thank you for your info – I’ve definitely picked up something new from right here. I did on the other hand expertise several technical points using this website, as I experienced to reload the website a lot of instances prior to I may get it to load properly. I had been puzzling over in case your web hosting is OK? Now not that I’m complaining, but sluggish loading circumstances occasions will very frequently have an effect on your placement in google and can harm your quality score if advertising and ***********|advertising|advertising|advertising and *********** with Adwords. Anyway I’m including this RSS to my email and can look out for a lot more of your respective interesting content. Make sure you update this once more soon..

  12. I regard something really special in this website.

  13. memopezil's avatar memopezil says:

    Fantastic items from you, man. I have be aware your stuff prior to and you are just too wonderful. I actually like what you’ve received here, certainly like what you’re saying and the way in which by which you assert it. You’re making it enjoyable and you still care for to stay it wise. I can’t wait to learn far more from you. This is actually a terrific web site.

  14. Fobertnap's avatar Fobertnap says:

    The discussion here feels very smooth and easy to follow, because the ideas are introduced clearly and the overall tone remains calm, positive, and inviting for readers who want to participate in the conversation.

    fastest withdrawal online casino canada

  15. I think this is among the most significant info for me. And i am glad reading your article. But wanna remark on few general things, The web site style is great, the articles is really excellent :D. Good job, cheers

  16. Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you can do with a few pics to drive the message home a little bit, but instead of that, this is wonderful blog. A fantastic read. I will definitely be back.

  17. memopezil's avatar memopezil says:

    I am glad to be a visitant of this stark web site! , thankyou for this rare info ! .

  18. klik di sini's avatar klik di sini says:

    There are some interesting points in time on this article however I don’t know if I see all of them middle to heart. There may be some validity but I will take maintain opinion till I look into it further. Good article , thanks and we would like extra! Added to FeedBurner as nicely

  19. visiflora's avatar visiflora says:

    Thank you for any other informative blog. The place else could I get that kind of info written in such a perfect means? I have a project that I am just now operating on, and I’ve been at the look out for such info.

  20. LewisGor's avatar LewisGor says:

    I am very glad I found this page, as the information provided here is exactly what I was searching for. It is a highly clear, universally applicable summary that perfectly balances substance and clear explanation without leaning toward any specific bias.

    casino en ligne retrait instantane

  21. I have learn a few just right stuff here. Certainly value bookmarking for revisiting. I surprise how a lot attempt you place to make this type of fantastic informative web site.

  22. prostadine's avatar prostadine says:

    Great article and straight to the point. I am not sure if this is in fact the best place to ask but do you people have any ideea where to hire some professional writers? Thanks in advance 🙂

  23. This blog is definitely rather handy since I’m at the moment creating an internet floral website – although I am only starting out therefore it’s really fairly small, nothing like this site. Can link to a few of the posts here as they are quite. Thanks much. Zoey Olsen

  24. I will immediately grab your rss as I can not find your email subscription hyperlink or newsletter service. Do you’ve any? Please allow me know so that I could subscribe. Thanks.

  25. Stephenviaps's avatar Stephenviaps says:

    Finding content that strikes the perfect balance between being detailed and remaining simple to follow is a rare treat. Thank you for sharing this wonderfully organized summary with us.

    BetWay

  26. LewisGor's avatar LewisGor says:

    This post creates a really pleasant reading experience because the wording feels smooth, the pacing stays smooth, and the overall discussion remains interesting without becoming too complicated to follow closely.

    meilleur site paris sportif hors arjel

  27. Free preview's avatar Free preview says:

    It’s like you read my thoughts!

  28. I really wanted to jot down a quick note to say thanks to you for those marvelous tips and hints you are giving on this website. My rather long internet search has now been honored with incredibly good concept to go over with my colleagues. I ‘d express that we visitors actually are undoubtedly fortunate to exist in a great site with so many lovely professionals with useful tips and hints. I feel very privileged to have discovered your entire website and look forward to tons of more awesome minutes reading here. Thanks again for all the details.

  29. Wonderful paintings! That is the kind of info that are supposed to be shared around the net. Disgrace on the search engines for now not positioning this submit higher! Come on over and consult with my web site . Thank you =)

  30. Saved as a favorite, I really like your blog!

  31. I’m really enjoying the design and layout of your blog. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a designer to create your theme? Excellent work!

  32. My brother suggested I might like this web site. He was once entirely right. This submit truly made my day. You cann’t consider simply how a lot time I had spent for this information! Thank you!

Comments are closed.