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! I just wish to give a huge thumbs up for the good info you have here on this post. I will be coming again to your weblog for extra soon.

  2. As I website owner I believe the subject material here is real superb, thankyou for your efforts.

  3. Hey, you used to write fantastic, but the last several posts have been kinda boringK I miss your tremendous writings. Past several posts are just a bit out of track! come on!

  4. toto macau's avatar toto macau says:

    I savor, lead to I discovered exactly what I was having a look for. You have ended my 4 day lengthy hunt! God Bless you man. Have a nice day. Bye

  5. I was wondering if you ever thought of changing the page layout of your blog? 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 one or two pictures. Maybe you could space it out better?

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

  7. Woh I love your posts, saved to my bookmarks! .

  8. jackwin77's avatar jackwin77 says:

    You are my breathing in, I own few blogs and occasionally run out from brand :). “Actions lie louder than words.” by Carolyn Wells.

  9. rajabandot's avatar rajabandot says:

    I¦ll right away grab your rss feed as I can’t to find your email subscription hyperlink or e-newsletter service. Do you’ve any? Please let me understand in order that I may subscribe. Thanks.

  10. I like this post, enjoyed this one thanks for putting up.

  11. Dealonomy's avatar Dealonomy says:

    Hey there, I think your blog might be having browser compatibility issues. When I look at your website in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, awesome blog!

  12. Some really rattling work on behalf of the owner of this website , dead great subject matter.

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

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

  15. I enjoy the efforts you have put in this, appreciate it for all the great articles.

  16. I really appreciate this post. I have been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thx again

  17. Very interesting details you have mentioned, thanks for posting.

  18. I am continuously looking online for ideas that can assist me. Thanks!

  19. Thanks for your posting. I also feel that laptop computers have gotten more and more popular lately, and now tend to be the only kind of computer utilised in a household. The reason is that at the same time they are becoming more and more affordable, their computing power is growing to the point where there’re as strong as pc’s from just a few in years past.

  20. 4d's avatar 4d says:

    Amazing! This blog looks exactly like my old one! It’s on a completely different subject but it has pretty much the same layout and design. Superb choice of colors!

  21. My spouse and I absolutely love your blog and find many of your post’s to be what precisely I’m looking for. Does one offer guest writers to write content for yourself? I wouldn’t mind publishing a post or elaborating on a lot of the subjects you write related to here. Again, awesome web log!

  22. Hmm is anyone else experiencing problems with the pictures on this blog loading? I’m trying to figure out if its a problem on my end or if it’s the blog. Any suggestions would be greatly appreciated.

  23. hello!,I like your writing very much! share we communicate more about your post on AOL? I need an expert on this area to solve my problem. May be that’s you! Looking forward to see you.

  24. sakongtoto's avatar sakongtoto says:

    Hey! Would you mind if I share your blog with my zynga group? There’s a lot of folks that I think would really enjoy your content. Please let me know. Thanks

  25. sakong toto's avatar sakong toto says:

    Really excellent info can be found on site. “Often the test of courage is not to die but to live.” by Conte Vittorio Alfieri.

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

  27. sakong toto's avatar sakong toto says:

    Woah! I’m really enjoying the template/theme of this site. It’s simple, yet effective. A lot of times it’s hard to get that “perfect balance” between user friendliness and appearance. I must say that you’ve done a awesome job with this. In addition, the blog loads super fast for me on Internet explorer. Excellent Blog!

  28. Thanks for this post, I am a big big fan of this site would like to continue updated.

  29. hey there and thank you for your info – I’ve certainly picked up something new from right here. I did however expertise a few technical points using this site, 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 host 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 ads and marketing with Adwords. Anyway I am adding this RSS to my email and can look out for a lot more of your respective fascinating content. Ensure that you update this again very soon..

  30. Its such as you learn my thoughts! You seem to understand so much approximately this, like you wrote the book in it or something. I believe that you could do with some to power the message house a bit, however other than that, that is wonderful blog. A fantastic read. I’ll definitely be back.

  31. Have you heard about ThyraFemme Balance? This natural supplement is becoming a sensation among women worldwide because it provides a real, safe, and natural solution for those struggling with hormonal imbalance, slow metabolism, weight gain, fatigue, and lack of energy.

  32. Just want to say your article is as surprising. The clearness in your post is just nice and i can assume you’re an expert on this subject. Well with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please keep up the rewarding work.

  33. Very good website you have here but I was curious about if you knew of any forums that cover the same topics talked about here? I’d really like to be a part of online community where I can get feedback from other experienced people that share the same interest. If you have any recommendations, please let me know. Thank you!

  34. An interesting discussion is worth comment. I think that you should write more on this topic, it might not be a taboo subject but generally people are not enough to speak on such topics. To the next. Cheers

  35. pamanempire's avatar pamanempire says:

    You actually make it seem so easy with your presentation but I find this topic to be really something that I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it!

  36. akongcuan's avatar akongcuan says:

    Wow, wonderful weblog format! How long have you ever been running a blog for? you make running a blog look easy. The entire glance of your site is great, as neatly as the content!

  37. With havin so much written content do you ever run into any problems of plagorism or copyright infringement? My site has a lot of exclusive content I’ve either authored myself or outsourced but it seems a lot of it is popping it up all over the internet without my permission. Do you know any ways to help prevent content from being stolen? I’d truly appreciate it.

  38. Thank you for the auspicious writeup. It in fact used to be a entertainment account it. Look complicated to far delivered agreeable from you! By the way, how can we keep in touch?

  39. togel macau's avatar togel macau says:

    Fantastic site. Plenty of useful info here. I am sending it to some buddies ans additionally sharing in delicious. And obviously, thanks to your effort!

  40. You made some respectable factors there. I looked on the web for the problem and located most people will go together with with your website.

  41. akongcuan's avatar akongcuan says:

    Thank you for sharing superb informations. Your site is very cool. I am impressed by the details that you’ve on this website. It reveals how nicely you perceive this subject. Bookmarked this website page, will come back for extra articles. You, my friend, ROCK! I found simply the information I already searched all over the place and simply could not come across. What a great web site.

  42. This article is absolutely incredible! The author has done a tremendous job of conveying the information in an engaging and informative manner. I can’t thank him enough for offering such valuable insights that have undoubtedly enriched my awareness in this topic. Kudos to him for crafting such a gem!

  43. Today, I went to the beach front with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!

  44. hptoto's avatar hptoto says:

    I do enjoy the manner in which you have presented this specific challenge and it does indeed supply me some fodder for thought. However, because of what I have witnessed, I only hope as the actual feed-back pack on that people today continue to be on issue and don’t get started on a tirade of some other news of the day. Yet, thank you for this fantastic point and though I do not concur with the idea in totality, I respect your standpoint.

  45. link gacor78's avatar link gacor78 says:

    Hi! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?

  46. situs togel's avatar situs togel says:

    Appreciate it for this wondrous post, I am glad I discovered this site on yahoo.

  47. situs toto's avatar situs toto says:

    I like this web blog so much, saved to bookmarks.

  48. I like this post, enjoyed this one thankyou for putting up.

  49. I love reading and I think this website got some really useful stuff on it! .

  50. Dead composed written content, Really enjoyed looking through.

Comments are closed.