Modern C# Part 3 – Switch Expressions

I admit it, I’ve struggled with pattern matching. In the next few blog posts I’ll explore this magic, starting today with switch expressions (not to be confused with switch statements).

The type of switch we’re familiar with is the switch statement:

namespace switchStatement;

internal class Program
{
   static void Main(string[] args)
   {
      string day = string.Empty;
      day = GetDay(2);
      Console.WriteLine(day);
   }

   public static string GetDay(int dayNum)
   {
      string dayName;
      switch (dayNum)
      {
         case 0:
            dayName = "Sunday";
            break;
         case 1:
            dayName = "Monday";
            break;
         case 2:
            dayName = "Tuesday";
            break;
         case 3:
            dayName = "Wednesday";
            break;
         case 4:
            dayName = "Thursday";
            break;
         case 5:
            dayName = "Friday";
            break;
         case 6:
            dayName = "Saturday";
            break;
         default:
            dayName = "Invalid day number";
            break;
      }
      return dayName;
   }
}

This will return Tuesday.

A switch expression has a slightly different syntax, but more important, it matches on a pattern. I’m going to use the example from Microsoft Learning (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression) and take it apart

public static class SwitchExample
{
    public enum Direction
    {
        Up,
        Down,
        Right,
        Left
    }

    public enum Orientation
    {
        North,
        South,
        East,
        West
    }

    public static Orientation ToOrientation(Direction direction) => direction switch
    {
        Direction.Up    => Orientation.North,
        Direction.Right => Orientation.East,
        Direction.Down  => Orientation.South,
        Direction.Left  => Orientation.West,
        _ => throw new ArgumentOutOfRangeException(nameof(direction), $"Not expected direction value: {direction}"),
    };

    public static void Main()
    {
        var direction = Direction.Right;
        Console.WriteLine($"Map view direction is {direction}");
        Console.WriteLine($"Cardinal orientation is {ToOrientation(direction)}");
    }
}

The output of this is

Map view direction is Right
Cardinal orientation is East

The method ToOrientation takes a Direction and calls the switch expression (notice the placement of the keyword switch).

It then sets up the Direction to Orientation pattern matching. For example, it establishes that if the passed in parameter is Direction.Up (that is, the Up enumerated constant) then it is to be converted to Orientation.North, and so forth. (The underscore is a new way of indicating no value, or in this case, the default).

The various expressions are called “arms” and are separated by commas. Each arm contains a pattern and an expression. In the first arm, Direction.Up returns the expression Orientation.North.

It is this pattern matching that I’ll be exploring in the next few blog posts.

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#, Mini-Tutorial. Bookmark the permalink.

1,136 Responses to Modern C# Part 3 – Switch Expressions

  1. fantastic points altogether, you simply gained a new reader. What would you suggest about your post that you made some days ago? Any positive?

  2. malware's avatar malware says:

    Hello, Neat post. There is a problem with your website in web explorer, could check thisK IE still is the market leader and a good component to other people will leave out your excellent writing because of this problem.

  3. bank soal's avatar bank soal says:

    Just wanna input on few general things, The website style and design is perfect, the subject material is real fantastic. “Drop the question what tomorrow may bring, and count as profit every day that fate allows you.” by Horace.

  4. nextogel's avatar nextogel says:

    obviously like your web-site however you have to take a look at the spelling on several of your posts. Several of them are rife with spelling problems and I find it very bothersome to inform the reality then again I will certainly come again again.

  5. Hello.This article was really remarkable, particularly since I was looking for thoughts on this issue last Wednesday.

  6. malware's avatar malware says:

    I discovered your blog site on google and check a few of your early posts. Continue to keep up the very good operate. I just additional up your RSS feed to my MSN News Reader. Seeking forward to reading more from you later on!…

  7. nextogel's avatar nextogel says:

    After examine a couple of of the weblog posts in your website now, and I truly like your manner of blogging. I bookmarked it to my bookmark website list and will likely be checking back soon. Pls try my website as effectively and let me know what you think.

  8. There are definitely numerous particulars like that to take into consideration. That may be a great level to convey up. I offer the ideas above as normal inspiration but clearly there are questions like the one you carry up the place a very powerful thing shall be working in sincere good faith. I don?t know if greatest practices have emerged round issues like that, but I’m certain that your job is clearly recognized as a fair game. Both boys and girls really feel the influence of only a moment?s pleasure, for the remainder of their lives.

  9. kopitogel's avatar kopitogel says:

    Hello. excellent job. I did not imagine this. This is a fantastic story. Thanks!

  10. I am continually browsing online for posts that can benefit me. Thx!

  11. kopitogel's avatar kopitogel says:

    Having read this I thought it was very informative. I appreciate you taking the time and effort to put this article together. I once again find myself spending way to much time both reading and commenting. But so what, it was still worth it!

  12. Its superb as your other posts : D, thankyou for putting up. “The real hero is always a hero by mistake he dreams of being an honest coward like everybody else.” by Umberto Eco.

  13. I’ve been absent for a while, but now I remember why I used to love this site. Thank you, I will try and check back more often. How frequently you update your web site?

  14. http://www.factorytinsigns.com is 100 Trusted Global Metal Vintage Tin Signs Online Shop. We have been selling art and décor online worldwide since 2008. Started in Sydney, Australia. 2000+ Tin Beer Signs, Outdoor Metal Wall Art, Business Tin Signs, Vintage Metal Signs to choose from. 100 Premium Quality Artwork. Up-to 40 OFF Sale Store-wide. Fast Shipping USA, Canada, UK, Australia, New Zealand, Europe.

  15. Great awesome issues here. I?¦m very satisfied to peer your article. Thanks so much and i’m looking ahead to contact you. Will you please drop me a e-mail?

  16. I was just searching for this info for a while. After six hours of continuous Googleing, finally I got it in your site. I wonder what is the lack of Google strategy that don’t rank this type of informative websites in top of the list. Generally the top sites are full of garbage.

  17. I do consider all of the ideas you’ve offered on your post. They’re really convincing and can certainly work. Still, the posts are very quick for starters. May just you please extend them a little from subsequent time? Thank you for the post.

  18. I dugg some of you post as I cogitated they were handy invaluable

  19. I like this web site so much, saved to favorites. “To hold a pen is to be at war.” by Francois Marie Arouet Voltaire.

  20. I have not checked in here for some time as I thought it was getting boring, but the last several posts are great quality so I guess I will add you back to my daily bloglist. You deserve it my friend 🙂

  21. I see something truly special in this internet site.

  22. ojwin7's avatar ojwin7 says:

    I like your writing style really loving this internet site.

  23. Thanks for your write-up. Another factor is that to be a photographer entails not only problem in recording award-winning photographs but also hardships in getting the best camera suited to your requirements and most especially issues in maintaining the quality of your camera. This is certainly very correct and obvious for those photography fans that are directly into capturing this nature’s exciting scenes — the mountains, the actual forests, the particular wild and the seas. Visiting these adventurous places surely requires a video camera that can meet the wild’s tough natural environment.

  24. Thanks for another magnificent post. Where else could anybody get that kind of info in such an ideal way of writing? I have a presentation next week, and I’m on the look for such information.

  25. I am not really wonderful with English but I come up this very easygoing to read .

  26. olxtoto's avatar olxtoto says:

    Of course, what a splendid blog and illuminating posts, I will bookmark your blog.All the Best!

  27. click here's avatar click here says:

    I have been examinating out a few of your posts and it’s pretty clever stuff. I will make sure to bookmark your blog.

  28. I am typically to blogging and i really admire your content. The article has actually peaks my interest. I’m going to bookmark your web site and maintain checking for brand spanking new information.

  29. raja botak's avatar raja botak says:

    Please let me know if you’re looking for a article author for your site. You have some really great articles and I feel I would be a good asset. If you ever want to take some of the load off, I’d love to write some material for your blog in exchange for a link back to mine. Please shoot me an email if interested. Many thanks!

  30. vps free's avatar vps free says:

    I have been surfing online more than 3 hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my opinion, if all site owners and bloggers made good content as you did, the net will be a lot more useful than ever before.

  31. komik dewasa's avatar komik dewasa says:

    naturally like your web site but you have to test the spelling on quite a few of your posts. Several of them are rife with spelling problems and I to find it very bothersome to inform the truth then again I will definitely come again again.

  32. situs togel's avatar situs togel says:

    hey there and thank you for your info – I have definitely picked up something new from right here. I did however expertise several technical issues using this website, as I experienced to reload the web site a lot of times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I am complaining, but sluggish loading instances times will often affect your placement in google and can damage your high quality score if advertising and marketing with Adwords. Well I’m adding this RSS to my email and could look out for much more of your respective intriguing content. Make sure you update this again soon..

  33. I am forever thought about this, appreciate it for putting up.

  34. Very interesting info !Perfect just what I was looking for!

  35. I will immediately grab your rss feed as I can not find your e-mail subscription link or newsletter service. Do you’ve any? Please let me know so that I could subscribe. Thanks.

  36. I like forgathering utile info, this post has got me even more info! .

  37. wbo777's avatar wbo777 says:

    Hello there! This is kind of off topic but I need some guidance from an established blog. Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about creating my own but I’m not sure where to begin. Do you have any ideas or suggestions? Appreciate it

  38. I truly appreciate this post. I have been looking all over for this! Thank goodness I found it on Bing. You’ve made my day! Thanks again!

  39. hepato burn's avatar hepato burn says:

    I was just looking for this info for some time. After 6 hours of continuous Googleing, at last I got it in your site. I wonder what’s the lack of Google strategy that do not rank this type of informative sites in top of the list. Generally the top sites are full of garbage.

  40. slot terbaru's avatar slot terbaru says:

    Hello, i think that i saw you visited my blog thus i came to “return the favor”.I am trying to find things to enhance my website!I suppose its ok to use a few of your ideas!!

  41. slot qris's avatar slot qris says:

    What i don’t understood is in reality how you are no longer actually much more well-liked than you may be now. You are very intelligent. You realize thus considerably in relation to this matter, made me in my view imagine it from numerous numerous angles. Its like men and women aren’t involved unless it is one thing to accomplish with Woman gaga! Your individual stuffs excellent. At all times handle it up!

  42. Great info and right to the point. I am not sure if this is in fact the best place to ask but do you guys have any thoughts on where to employ some professional writers? Thx 🙂

  43. Thank you so much for providing individuals with an extraordinarily wonderful chance to read from this blog. It is always so amazing plus jam-packed with a lot of fun for me personally and my office friends to visit your web site at a minimum three times in a week to learn the latest issues you have got. And indeed, I’m just usually satisfied with the special solutions served by you. Selected 1 tips on this page are clearly the most beneficial we have had.

  44. Im not sure the place you’re getting your information, but great topic. I needs to spend some time studying more or figuring out more. Thank you for fantastic info I used to be searching for this info for my mission.

  45. akongcuan's avatar akongcuan says:

    My brother recommended I might like this web site. He was totally right. This post truly made my day. You can not imagine just how much time I had spent for this info! Thanks!

  46. Thanks , I have just been searching for info approximately this subject for a long time and yours is the greatest I have came upon till now. However, what in regards to the bottom line? Are you positive concerning the supply?

  47. What’s Happening i am new to this, I stumbled upon this I’ve found It absolutely useful and it has aided me out loads. I hope to contribute & aid other users like its aided me. Great job.

  48. This actually answered my drawback, thank you!

  49. Well I really liked reading it. This post offered by you is very effective for good planning.

Comments are closed.