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. kakahoki's avatar kakahoki says:

    hi!,I like your writing so so much! proportion we be in contact more about your article on AOL? I require a specialist in this house to solve my problem. Maybe that’s you! Looking forward to peer you.

  2. I am not sure where you’re getting your information, but great topic. I needs to spend some time learning more or understanding more. Thanks for fantastic information I was looking for this information for my mission.

  3. gdzie mozna kupic prawo jazdy z wpisem do rejestru, kupić prawo jazdy, legalne prawo jazdy do kupienia, kupię prawo jazdy, jak załatwić prawo jazdy, bez egzaminu, jak kupić prawo jazdy, czy można kupić prawo jazdy, legalne prawo jazdy do kupienia 2025, pomogę zdać egzamin na prawo jazdy, prawo jazdy bez egzaminu, gdzie kupić prawo jazdy bez egzaminu, gdzie kupić prawo jazdy na lewo, jak kupić prawo jazdy w niemczech, gdzie kupic prawo jazdy legalnie, kupić prawo jazdy b, pomogę zdać egzamin na prawo jazdy, gdzie można kupić prawo jazdy z wpisem do rejestru forum, prawo jazdy płatne przy odbiorze, prawo jazdy czechy kupno, w jakim kraju można kupić prawo jazdy, pomogę załatwić prawo jazdy w uk, sprzedam prawo jazdy z wpisem bez zaliczek, jak kupić prawo jazdy w uk, ile kosztuje prawo jazdy na lewo?, 98iuh

  4. pestoto's avatar pestoto says:

    There is obviously a lot to know about this. I assume you made various nice points in features also.

  5. macau jitu's avatar macau jitu says:

    I think you have noted some very interesting details , thankyou for the post.

  6. I do not even know how I ended up here, but I thought this post was good. I don’t know who you are but certainly you are going to a famous blogger if you aren’t already 😉 Cheers!

  7. kaka hoki's avatar kaka hoki says:

    Hi there, You’ve done an incredible job. I’ll definitely digg it and personally suggest to my friends. I am sure they’ll be benefited from this site.

  8. quiz4d slot's avatar quiz4d slot says:

    It is really a great and useful piece of information. I am glad that you shared this helpful info with us. Please keep us up to date like this. Thank you for sharing.

  9. Really nice design and wonderful subject matter, very little else we require : D.

  10. We are a bunch of volunteers and opening a brand new scheme in our community. Your web site provided us with valuable information to paintings on. You have done an impressive process and our entire neighborhood shall be grateful to you.

  11. Glad to be one of several visitants on this awing website : D.

  12. naga empire's avatar naga empire says:

    Hey there just wanted to give you a quick heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different web browsers and both show the same outcome.

  13. Hi there, I found your web site via Google while searching for a related topic, your website came up, it looks good. I’ve bookmarked it in my google bookmarks.

  14. The next time I read a blog, I hope that it doesnt disappoint me as much as this one. I mean, I know it was my choice to read, but I actually thought youd have something interesting to say. All I hear is a bunch of whining about something that you could fix if you werent too busy looking for attention.

  15. lotto champ's avatar lotto champ says:

    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.

  16. macau 4d's avatar macau 4d says:

    I’m not sure where you are getting your info, but good topic. I needs to spend some time learning much more or understanding more. Thanks for magnificent info I was looking for this information for my mission.

  17. This design is steller! You most certainly know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Fantastic job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!

  18. laser 1490's avatar laser 1490 says:

    When I originally commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Thanks!

  19. 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.

  20. 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.

  21. alexaslot138's avatar alexaslot138 says:

    Good write-up, I?¦m regular visitor of one?¦s web site, maintain up the excellent operate, and It is going to be a regular visitor for a lengthy time.

  22. raja botak's avatar raja botak says:

    Thanks for sharing excellent informations. Your website is so cool. I’m impressed by the details that you have on this site. It reveals how nicely you perceive this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found just the info I already searched all over the place and simply could not come across. What an ideal website.

  23. alexaslot138's avatar alexaslot138 says:

    It’s actually a nice and useful piece of info. I’m glad that you shared this useful info with us. Please keep us informed like this. Thanks for sharing.

  24. Many men who have tried the blue salt trick report increased stamina, better performance, and a renewed sense of confidence.

  25. empire88's avatar empire88 says:

    I consider something genuinely interesting about your website so I saved to my bookmarks.

  26. I do agree with all of the ideas you have presented in your post. They’re really convincing and will definitely work. Still, the posts are too short for novices. Could you please extend them a bit from next time? Thanks for the post.

  27. janome's avatar janome says:

    Some really quality posts on this internet site, saved to bookmarks.

  28. pausempire's avatar pausempire says:

    Do you mind if I quote a few of your posts as long as I provide credit and sources back to your weblog? My website is in the very same area of interest as yours and my visitors would definitely benefit from some of the information you present here. Please let me know if this ok with you. Thanks!

  29. The Pink Salt Trick is a minimalist but effective morning routine: Just drink a glass of lukewarm water mixed with a pinch of Himalayan pink salt as soon as you wake up.

  30. Thanks for your personal marvelous posting! I actually enjoyed reading it, you may be a great author.I will make certain to bookmark your blog and definitely will come back very soon. I want to encourage yourself to continue your great posts, have a nice afternoon!

  31. Mitolyn's avatar Mitolyn says:

    There are actually lots of details like that to take into consideration. That is a great point to deliver up. I supply the ideas above as normal inspiration but clearly there are questions just like the one you convey up the place the most important factor will likely be working in honest good faith. I don?t know if greatest practices have emerged around issues like that, however I’m positive that your job is clearly recognized as a fair game. Both girls and boys really feel the impression of only a second’s pleasure, for the rest of their lives.

  32. The Pink Salt Trick is a minimalist but effective morning routine: Just drink a glass of lukewarm water mixed with a pinch of Himalayan pink salt as soon as you wake up.

  33. data macau's avatar data macau says:

    Thank you for sharing excellent informations. Your website is so cool. I am impressed by the details that you?¦ve on this blog. It reveals how nicely you perceive this subject. Bookmarked this web page, will come back for extra articles. You, my pal, ROCK! I found simply the information I already searched all over the place and just couldn’t come across. What a perfect web site.

  34. The Pink Salt Trick is a minimalist but effective morning routine: Just drink a glass of lukewarm water mixed with a pinch of Himalayan pink salt as soon as you wake up.

  35. Hepato Burn's avatar Hepato Burn says:

    Just wish to say your article is as surprising. The clarity on your submit is just great and that i could think you are knowledgeable on this subject. Fine with your permission let me to seize your RSS feed to keep updated with coming near near post. Thanks a million and please continue the enjoyable work.

  36. Wow that was odd. I just wrote an extremely long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyhow, just wanted to say superb blog!

  37. But wanna remark on few general things, The website layout is perfect, the articles is rattling great : D.

  38. Nice read, I just passed this onto a colleague who was doing a little research on that. And he actually bought me lunch as I found it for him smile Thus let me rephrase that: Thanks for lunch! “We steal if we touch tomorrow. It is God’s.” by Henry Ward Beecher.

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

  40. This internet site is my aspiration, really good pattern and perfect articles.

  41. Great write-up, I’m regular visitor of one’s web site, maintain up the nice operate, and It’s going to be a regular visitor for a long time.

  42. What i do not realize is if truth be told how you’re now not actually a lot more well-favored than you may be right now. You are so intelligent. You understand thus considerably in terms of this topic, made me in my view imagine it from numerous varied angles. Its like women and men are not interested except it’s one thing to accomplish with Girl gaga! Your individual stuffs outstanding. At all times deal with it up!

  43. Great website. Lots of helpful info here. I’m sending it to a few buddies ans also sharing in delicious. And of course, thank you in your effort!

  44. Well I really liked studying it. This subject offered by you is very useful for proper planning.

  45. Tonic Greens's avatar Tonic Greens says:

    I enjoy you because of all your effort on this blog. Betty really loves going through investigation and it’s really easy to see why. A lot of people notice all regarding the lively ways you offer useful techniques on the web site and in addition foster response from some others on this theme while my child is without a doubt starting to learn a great deal. Have fun with the remaining portion of the year. You’re carrying out a terrific job.

  46. pestoto's avatar pestoto says:

    You are my aspiration, I have few blogs and very sporadically run out from to post : (.

  47. Eva Bloom's avatar Eva Bloom says:

    You should take part in a contest for one of the best blogs on the web. I will recommend this site!

  48. Hello there! This is my first visit to your blog! We are a collection of volunteers and starting a new project in a community in the same niche. Your blog provided us valuable information to work on. You have done a extraordinary job!

  49. Eva Bloom's avatar Eva Bloom says:

    Thankyou for this marvelous post, I am glad I noticed this internet site on yahoo.

  50. An fascinating dialogue is value comment. I feel that you need to write extra on this subject, it might not be a taboo topic however generally people are not sufficient to speak on such topics. To the next. Cheers

Comments are closed.