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. Hey very cool site!! Man .. Beautiful .. Superb .. I will bookmark your website and take the feeds also…I am happy to find so many useful info here within the put up, we need work out extra strategies on this regard, thanks for sharing. . . . . .

  2. togel online's avatar togel online says:

    It is perfect time to make a few plans for the future and it is time to be happy. I’ve learn this put up and if I may just I wish to suggest you some attention-grabbing issues or tips. Maybe you could write subsequent articles relating to this article. I desire to read more issues about it!

  3. An impressive share, I just given this onto a colleague who was doing a little analysis on this. And he in fact bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If possible, as you become expertise, would you mind updating your blog with more details? It is highly helpful for me. Big thumb up for this blog post!

  4. It is truly a nice and helpful piece of info. I¦m happy that you simply shared this useful info with us. Please keep us up to date like this. Thank you for sharing.

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

  6. Your place is valueble for me. Thanks!…

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

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

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

  10. I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz answer back as I’m looking to create my own blog and would like to know where u got this from. many thanks

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

  12. I was reading some of your blog posts on this website and I conceive this site is very instructive! Continue posting.

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

  14. Good website! I really love how it is easy on my eyes and the data are well written. I’m wondering how I might be notified when a new post has been made. I have subscribed to your feed which must do the trick! Have a great day!

  15. This is a very good tips especially to those new to blogosphere, brief and accurate information… Thanks for sharing this one. A must read article.

  16. What’s Going down i am new to this, I stumbled upon this I’ve discovered It absolutely useful and it has helped me out loads. I hope to contribute & assist different customers like its helped me. Great job.

  17. pestoto's avatar pestoto says:

    I appreciate, lead to I discovered just what I was having a look for. You’ve ended my 4 day lengthy hunt! God Bless you man. Have a great day. Bye

  18. nextogel's avatar nextogel says:

    Woh I enjoy your content, saved to my bookmarks! .

  19. 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 in the future. All the best

  20. nextogel's avatar nextogel says:

    Pretty portion of content. I simply stumbled upon your web site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Anyway I will be subscribing for your augment or even I success you get right of entry to consistently rapidly.

  21. Of course, what a splendid site and revealing posts, I definitely will bookmark your blog.All the Best!

  22. There are some attention-grabbing deadlines on this article however I don’t know if I see all of them center to heart. There is some validity but I will take maintain opinion till I look into it further. Good article , thanks and we want more! Added to FeedBurner as nicely

  23. Right now it looks like Movable Type is the top blogging platform available right now. (from what I’ve read) Is that what you’re using on your blog?

  24. You are a very intelligent person!

  25. slot 1000's avatar slot 1000 says:

    Thanks for another excellent article. Where else could anybody get that kind of info in such a perfect way of writing? I’ve a presentation next week, and I am on the look for such information.

  26. mlbb top up's avatar mlbb top up says:

    Thank you for every other informative site. Where else may I get that type of information written in such an ideal way? I have a mission that I am just now working on, and I’ve been at the glance out for such information.

  27. Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is fantastic, let alone the content!

  28. Good post. I be taught something tougher on different blogs everyday. It’s going to all the time be stimulating to learn content material from other writers and observe a little something from their store. I’d desire to make use of some with the content material on my weblog whether or not you don’t mind. Natually I’ll offer you a link on your net blog. Thanks for sharing.

  29. I’m really impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you customize it yourself? Anyway keep up the excellent quality writing, it is rare to see a great blog like this one these days..

  30. Good article. It is quite unfortunate that over the last several years, the travel industry has had to fight terrorism, SARS, tsunamis, influenza, swine flu, plus the first ever entire global economic collapse. Through all this the industry has proven to be effective, resilient in addition to dynamic, finding new strategies to deal with trouble. There are always fresh issues and the opportunity to which the industry must once again adapt and act in response.

  31. Wonderful post but I was wondering if you could write a litte more on this subject? I’d be very grateful if you could elaborate a little bit further. Bless you!

  32. oma333's avatar oma333 says:

    You have brought up a very wonderful details , thanks for the post.

  33. Can I just say what a relief to find someone who actually knows what theyre talking about on the internet. You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I cant believe youre not more popular because you definitely have the gift.

  34. F*ckin’ tremendous things here. I’m very happy to look your post. Thank you so much and i’m looking forward to contact you. Will you please drop me a mail?

  35. toto's avatar toto 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

  36. indocair's avatar indocair says:

    Regards for this post, I am a big big fan of this site would like to proceed updated.

  37. You can certainly see your skills within the paintings you write. The sector hopes for even more passionate writers like you who are not afraid to mention how they believe. All the time go after your heart.

  38. Fantastic web site. Lots of useful information here. I?¦m sending it to several pals ans additionally sharing in delicious. And of course, thanks to your sweat!

  39. Valuable information. Lucky me I found your web site by accident, and I am shocked why this accident did not happened earlier! I bookmarked it.

  40. I like what you guys are up too. Such smart work and reporting! Carry on the excellent works guys I’ve incorporated you guys to my blogroll. I think it will improve the value of my site 🙂

  41. Lucio Mehta's avatar Lucio Mehta says:

    Thanks for the marvelous posting! I truly enjoyed reading it, you can be a great author.I will be sure to bookmark your blog and will often come back later in life. I want to encourage continue your great work, have a nice evening!

  42. Excellent web site. Plenty of useful information here. I’m sending it to some friends ans also sharing in delicious. And naturally, thanks for your sweat!

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

  44. I truly enjoy looking through on this web site, it contains fantastic posts. “One should die proudly when it is no longer possible to live proudly.” by Friedrich Wilhelm Nietzsche.

  45. I really like reading and I think this website got some really utilitarian stuff on it! .

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

  47. 光算科技's avatar 光算科技 says:

    Magnificent site. Plenty of helpful info here. I¦m sending it to some pals ans also sharing in delicious. And of course, thank you to your effort!

  48. Sweet blog! I found it while searching on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Thanks

  49. onewave's avatar onewave says:

    fantastic post, very informative. I wonder why the other experts of this sector don’t notice this. You should continue your writing. I am sure, you’ve a huge readers’ base already!

  50. Hello my loved one! I wish to say that this post is amazing, great written and include almost all important infos. I?¦d like to see extra posts like this .

Comments are closed.