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

    What i don’t realize is in truth how you’re now not actually a lot more smartly-preferred than you may be now. You’re so intelligent. You recognize therefore significantly with regards to this topic, made me in my view consider it from numerous varied angles. Its like men and women are not interested except it¦s one thing to accomplish with Girl gaga! Your individual stuffs outstanding. All the time deal with it up!

  2. kopitogel's avatar kopitogel says:

    hi!,I really like your writing so a lot! proportion we be in contact extra approximately your article on AOL? I need an expert in this house to solve my problem. May be that’s you! Taking a look ahead to peer you.

  3. I think this internet site holds some real wonderful info for everyone : D.

  4. kopitogel's avatar kopitogel says:

    I do like the way you have framed this problem and it really does supply us a lot of fodder for thought. On the other hand, coming from everything that I have experienced, I just wish as the opinions stack on that folks keep on issue and not get started on a soap box involving the news of the day. Yet, thank you for this outstanding piece and whilst I can not really agree with it in totality, I regard the perspective.

  5. I know this if off topic but I’m looking into starting my own weblog and was wondering what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web smart so I’m not 100 sure. Any suggestions or advice would be greatly appreciated. Appreciate it

  6. xem nba's avatar xem nba says:

    Very interesting info !Perfect just what I was searching for!

  7. sleeplean's avatar sleeplean says:

    Sleep Lean is a natural supplement designed to improve sleep quality and aid weight loss while you sleep.

  8. toto's avatar toto says:

    Definitely believe that which you stated. Your favorite reason appeared to be on the internet the easiest thing to be aware of. I say to you, I definitely get annoyed while people think about worries that they plainly don’t know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side effect , people can take a signal. Will likely be back to get more. Thanks

  9. nextogel's avatar nextogel says:

    Keep functioning ,terrific job!

  10. Lipovive acts on the metabolism, burning fat, reducing appetite, and providing more energy.

  11. Thank you a lot for providing individuals with an extremely spectacular possiblity to discover important secrets from this website. It is usually very pleasurable plus jam-packed with fun for me and my office co-workers to visit the blog minimum three times every week to see the latest guidance you will have. And lastly, I’m always motivated with the wonderful strategies you serve. Certain two tips in this article are essentially the most beneficial I have had.

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

  13. Hello, you used to write magnificent, but the last few posts have been kinda boring… I miss your tremendous writings. Past several posts are just a bit out of track! come on!

  14. nextogel's avatar nextogel says:

    Greetings! Very helpful advice on this article! It is the little changes that make the biggest changes. Thanks a lot for sharing!

  15. Howdy! Someone in my Facebook group shared this website with us so I came to give it a look. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers! Exceptional blog and fantastic design.

  16. Hello, i think that i noticed you visited my website thus i got here to ?return the choose?.I’m attempting to find issues to improve my website!I suppose its good enough to make use of some of your ideas!!

  17. nextogel's avatar nextogel says:

    I’d perpetually want to be update on new content on this site, saved to favorites! .

  18. Rattling good visual appeal on this website , I’d rate it 10 10.

  19. ekjp's avatar ekjp says:

    Thanks for the tips you are sharing on this blog. Another thing I’d really like to say is that often getting hold of copies of your credit score in order to inspect accuracy of each detail will be the first action you have to carry out in repairing credit. You are looking to clean up your credit history from destructive details faults that mess up your credit score.

  20. Some genuinely interesting points you have written.Aided me a lot, just what I was looking for : D.

  21. Peculiar article, totally what I wanted to find.

    Here is my web site … ereforce male enhancement

  22. pestoto's avatar pestoto says:

    We’re a group of volunteers and starting a new scheme in our community. Your web site provided us with valuable info to work on. You’ve done an impressive job and our entire community will be thankful to you.

  23. As a Newbie, I am constantly browsing online for articles that can aid me. Thank you

  24. After study a few of the blog posts on your website now, and I truly like your way of blogging. I bookmarked it to my bookmark website list and will be checking back soon. Pls check out my web site as well and let me know what you think.

  25. bandar togel's avatar bandar togel 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!

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

  27. Nice blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog shine. Please let me know where you got your design. Many thanks

  28. Nice post. I was checking constantly this blog and I am impressed! Very helpful information specifically the last part 🙂 I care for such information a lot. I was looking for this particular information for a very long time. Thank you and good luck.

  29. oab 2a fase's avatar oab 2a fase says:

    Do you have a spam problem on this website; I also am a blogger, and I was wanting to know your situation; we have developed some nice methods and we are looking to trade techniques with other folks, why not shoot me an e-mail if interested.

  30. I went over this website and I believe you have a lot of wonderful info , saved to favorites (:.

  31. Some genuinely nice and useful info on this site, as well I think the style and design has got superb features.

  32. Im not positive the place you’re getting your information, but good topic. I needs to spend some time finding out much more or understanding more. Thanks for fantastic information I used to be searching for this info for my mission.

  33. slot gacor's avatar slot gacor says:

    Well I sincerely enjoyed reading it. This subject provided by you is very helpful for accurate planning.

  34. Wow! Thank you! I constantly needed to write on my blog something like that. Can I take a portion of your post to my website?

  35. pestoto's avatar pestoto says:

    I always was concerned in this subject and still am, thankyou for posting.

  36. I was very pleased to search out this web-site.I needed to thanks to your time for this glorious learn!! I positively having fun with every little little bit of it and I’ve you bookmarked to check out new stuff you weblog post.

  37. pestoto's avatar pestoto says:

    I have learn several just right stuff here. Definitely worth bookmarking for revisiting. I surprise how much attempt you set to make any such great informative web site.

  38. Thank you for your entire efforts on this web page. Betty really loves carrying out investigations and it’s really obvious why. My partner and i learn all concerning the powerful medium you give rewarding solutions through the blog and in addition increase participation from other individuals on the subject matter plus our own simple princess is now starting to learn a lot. Have fun with the rest of the new year. You’re conducting a dazzling job.

  39. Hello! I just would like to give a huge thumbs up for the great info you have here on this post. I will be coming back to your blog for more soon.

  40. agen togel's avatar agen togel says:

    whoah this blog is great i love reading your posts. Keep up the good work! You know, a lot of people are looking around for this information, you could help them greatly.

  41. It’s hard to find knowledgeable people on this topic, but you sound like you know what you’re talking about! Thanks

  42. alexaslot's avatar alexaslot says:

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

  43. I love your writing style genuinely loving this internet site.

  44. I simply wished to say thanks once again. I do not know the things I would have created in the absence of the actual tricks shown by you about that area of interest. It had been a very distressing setting in my circumstances, however , noticing a new specialized manner you solved it took me to cry over contentment. I’m just happier for your advice and hope that you find out what an amazing job you were undertaking educating people today all through your web page. I know that you’ve never encountered all of us.

  45. Nice post. I was checking constantly this blog and I’m impressed! Very useful info particularly the last part 🙂 I care for such information a lot. I was looking for this certain information for a long time. Thank you and best of luck.

  46. I conceive this site has got very excellent pent content articles.

  47. Hey very nice web site!! Guy .. Beautiful .. Wonderful .. I’ll bookmark your web site and take the feeds alsoKI’m glad to find so many useful information right here in the post, we need work out more strategies on this regard, thanks for sharing. . . . . .

  48. ماركت's avatar ماركت says:

    Hello, i think that i saw you visited my website so i came to “return the favor”.I’m attempting to find things to improve my web site!I suppose its ok to use a few of your ideas!!

  49. alexaslot138's avatar alexaslot138 says:

    Pretty section of content. I just stumbled upon your weblog and in accession capital to assert that I get actually enjoyed account your blog posts. Any way I’ll be subscribing to your feeds and even I achievement you access consistently rapidly.

Comments are closed.