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

    Thanks for some other great article. Where else may anybody get that type of information in such a perfect means of writing? I’ve a presentation next week, and I am at the look for such info.

  2. I’m still learning from you, as I’m improving myself. I absolutely liked reading all that is posted on your website.Keep the tips coming. I liked it!

  3. I respect your work, appreciate it for all the good posts.

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

  5. slot terbaru's avatar slot terbaru says:

    I really enjoy studying on this internet site, it holds great blog posts. “We find comfort among those who agree with us–growth among those who don’t.” by Frank A. Clark.

  6. Heya i am for the first time here. I found this board and I to find It really helpful & it helped me out much. I am hoping to give something back and help others like you helped me.

  7. toto slot's avatar toto slot says:

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

  8. Great post. I was checking constantly this blog and I am impressed! Very useful information particularly the last part 🙂 I care for such information a lot. I was looking for this particular info for a very long time. Thank you and good luck.

  9. An interesting discussion is value comment. I believe that it’s best to write more on this matter, it may not be a taboo subject however usually people are not sufficient to speak on such topics. To the next. Cheers

  10. Hi my loved one! I wish to say that this article is amazing, nice written and come with approximately all important infos. I’d like to peer extra posts like this .

  11. I’ve recently started a web site, the information you provide on this website has helped me greatly. Thank you for all of your time & work.

  12. Naga303's avatar Naga303 says:

    An attention-grabbing discussion is value comment. I think that you should write extra on this topic, it might not be a taboo topic but usually people are not sufficient to speak on such topics. To the next. Cheers

  13. hello there and thank you for your information – I’ve definitely picked up something new from right here. I did however expertise a few technical points using this website, since I experienced to reload the web site lots of times previous to I could get it to load correctly. I had been wondering if your web hosting is OK? Not that I am complaining, but sluggish loading instances times will very frequently affect your placement in google and could damage your high quality score if advertising and marketing with Adwords. Anyway I’m adding this RSS to my email and can look out for much more of your respective fascinating content. Ensure that you update this again very soon..

  14. Utterly composed articles, Really enjoyed reading through.

  15. Absolutely written content material, thankyou for selective information.

  16. I think you have mentioned some very interesting points, thankyou for the post.

  17. Bk8's avatar Bk8 says:

    I was recommended this website by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my difficulty. You are wonderful! Thanks!

  18. After all, what a great site and informative posts, I will upload inbound link – bookmark this web site? Regards, Reader.

  19. Some truly nice stuff on this site, I like it.

  20. slot online's avatar slot online says:

    I just couldn’t depart your site before suggesting that I extremely enjoyed the standard info a person provide for your visitors? Is gonna be back often in order to check up on new posts

  21. jello diet's avatar jello diet says:

    I am impressed with this internet site, real I am a big fan .

  22. macau's avatar macau says:

    Hmm it looks like your website ate my first comment (it was extremely long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to everything. Do you have any tips and hints for inexperienced blog writers? I’d genuinely appreciate it.

  23. Thanx for the effort, keep up the good work Great work, I am going to start a small Blog Engine course work using your site I hope you enjoy blogging with the popular BlogEngine.net.Thethoughts you express are really awesome. Hope you will right some more posts.

  24. Attractive portion of content. I simply stumbled upon your web site and in accession capital to say that I get in fact enjoyed account your weblog posts. Any way I will be subscribing in your feeds and even I fulfillment you get entry to consistently rapidly.

  25. situs toto's avatar situs toto says:

    Some times its a pain in the ass to read what blog owners wrote but this site is very user friendly! .

  26. In the awesome design of things you actually get a B+ with regard to effort and hard work. Exactly where you actually misplaced me personally was first on the specifics. As as the maxim goes, the devil is in the details… And that couldn’t be much more true here. Having said that, permit me tell you just what did do the job. Your writing is actually incredibly powerful which is possibly the reason why I am making the effort in order to opine. I do not really make it a regular habit of doing that. 2nd, whilst I can easily see a leaps in reasoning you make, I am not necessarily confident of exactly how you seem to connect the details that help to make the actual final result. For the moment I will, no doubt yield to your issue but trust in the future you actually link your facts better.

  27. olxtoto's avatar olxtoto says:

    Unquestionably believe that that you stated. Your favorite justification appeared to be on the net the simplest thing to have in mind of. I say to you, I certainly get irked at the same time as people think about issues that they plainly don’t know about. You managed to hit the nail upon the top and defined out the entire thing with no need side effect , people can take a signal. Will probably be again to get more. Thanks

  28. Hey! I just wish to give an enormous thumbs up for the good information you could have right here on this post. I might be coming back to your weblog for extra soon.

  29. olxtoto's avatar olxtoto says:

    hey there and thank you for your information – I’ve certainly picked up something new from right here. I did however expertise a few technical issues using this site, since I experienced to reload the web site lots of times previous to I could get it to load properly. I had been wondering if your web host is OK? Not that I’m complaining, but sluggish loading instances times will often affect your placement in google and can damage your high-quality score if ads and marketing with Adwords. Well I am adding this RSS to my e-mail and can look out for a lot more of your respective exciting content. Ensure that you update this again very soon..

  30. toto macau's avatar toto macau says:

    Good info. Lucky me I reach on your website by accident, I bookmarked it.

  31. klarmong3's avatar klarmong3 says:

    I like this site because so much useful material on here : D.

  32. I like this website so much, saved to favorites. “American soldiers must be turned into lambs and eating them is tolerated.” by Muammar Qaddafi.

  33. Zip Sprout's avatar Zip Sprout says:

    Simply desire to say your article is as amazing. The clarity in your post is just nice and i could assume you are an expert on this subject. Well with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please keep up the enjoyable work.

  34. slot online's avatar slot online says:

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

  35. Whats up are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any html coding expertise to make your own blog? Any help would be really appreciated!

  36. ceritoto's avatar ceritoto says:

    I think other web-site proprietors should take this site as an model, very clean and wonderful user friendly style and design, as well as the content. You’re an expert in this topic!

  37. Those are yours alright! . We at least need to get these people stealing images to start blogging! They probably just did a image search and grabbed them. They look good though!

  38. There is perceptibly a bunch to know about this. I believe you made some nice points in features also.

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

  40. Hey! I could have sworn I’ve been to this blog before but after checking through some of the post I realized it’s new to me. Anyhow, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

  41. Greetings! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly? My web site looks weird when browsing from my apple iphone. I’m trying to find a template or plugin that might be able to correct this issue. If you have any recommendations, please share. Many thanks!

  42. ceritoto's avatar ceritoto says:

    Very fantastic visual appeal on this internet site, I’d rate it 10 10.

  43. slot demo's avatar slot demo says:

    You really make it seem so easy along with your presentation however I to find this topic to be actually something which I think I might by no means understand. It kind of feels too complex and very vast for me. I am taking a look forward on your subsequent publish, I will attempt to get the dangle of it!

  44. ket qua nba's avatar ket qua nba says:

    I have been absent for some time, but now I remember why I used to love this web site. Thanks, I will try and check back more often. How frequently you update your site?

  45. I was curious if you ever considered changing the page layout of your website? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 pictures. Maybe you could space it out better?

  46. I’m still learning from you, while I’m trying to reach my goals. I absolutely enjoy reading all that is written on your website.Keep the tips coming. I enjoyed it!

  47. ceritoto's avatar ceritoto says:

    Very nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed surfing around your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!

  48. 777pub's avatar 777pub says:

    I like this blog so much, saved to favorites.

  49. slot dana's avatar slot dana says:

    I like this web site so much, bookmarked. “Nostalgia isn’t what it used to be.” by Peter De Vries.

Comments are closed.