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. As soon as I observed this site I went on reddit to share some of the love with them.

  2. I conceive this internet site has got very excellent composed content content.

  3. I am extremely impressed with your writing skills as well as with the layout on your blog. Is this a paid theme or did you modify it yourself? Anyway keep up the excellent quality writing, it?s rare to see a great blog like this one these days..

  4. Thanks, I have recently been looking for info approximately this subject for a long time and yours is the greatest I’ve discovered till now. But, what about the conclusion? Are you positive in regards to the source?

  5. bidencash's avatar bidencash says:

    I was examining some of your articles on this internet site and I believe this web site is real instructive! Keep putting up.

  6. Lovely just what I was searching for.Thanks to the author for taking his time on this one.

  7. I’ve been exploring for a bit for any high quality articles or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this site. Reading this information So i’m happy to convey that I’ve a very good uncanny feeling I discovered just what I needed. I most certainly will make certain to don’t forget this web site and give it a glance on a constant basis.

  8. 71 games's avatar 71 games says:

    Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across. It extremely helps make reading your blog significantly easier.

  9. I will right away grab your rss feed as I can’t in finding your email subscription hyperlink or e-newsletter service. Do you have any? Kindly permit me understand in order that I could subscribe. Thanks.

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

  11. 21 game's avatar 21 game says:

    Hello! This is my first comment here so I just wanted to give a quick shout out and tell you I really enjoy reading your blog posts. Can you recommend any other blogs/websites/forums that go over the same subjects? Thank you!

  12. It¦s actually a nice and helpful piece of info. I¦m happy that you shared this helpful information with us. Please keep us informed like this. Thanks for sharing.

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

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

  15. I am extremely impressed along with your writing skills as smartly as with the format on your blog. Is that this a paid topic or did you modify it yourself? Either way stay up the excellent quality writing, it is uncommon to peer a great blog like this one these days..

  16. certainly like your web-site but you have to take a look at the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very bothersome to tell the reality nevertheless I¦ll certainly come again again.

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

    I conceive this website has got some really excellent information for everyone : D.

  18. lindaydulce's avatar lindaydulce says:

    I am so happy to read this. This is the kind of manual that needs to be given and not the random misinformation that’s at the other blogs. Appreciate your sharing this best doc.

  19. sheet metal's avatar sheet metal says:

    Some truly good info , Sword lily I detected this.

  20. I truly appreciate this post. I have been looking everywhere for this! Thank goodness I found it on Bing. You’ve made my day! Thank you again

  21. I would like to thnkx for the efforts you have put in writing this blog. I am hoping the same high-grade blog post from you in the upcoming as well. In fact your creative writing abilities has inspired me to get my own blog now. Really the blogging is spreading its wings quickly. Your write up is a good example of it.

  22. Hi , I do believe this is an excellent blog. I stumbled upon it on Yahoo , i will come back once again. Money and freedom is the best way to change, may you be rich and help other people.

  23. Very efficiently written information. It will be useful to anyone who employess it, as well as myself. Keep doing what you are doing – i will definitely read more posts.

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

  25. You really make it appear so easy along with your presentation however I to find this matter to be actually one thing which I believe I might never understand. It kind of feels too complicated and very large for me. I’m having a look forward for your subsequent publish, I will attempt to get the cling of it!

  26. japritoto's avatar japritoto says:

    Hey there! I know this is somewhat off topic but I was wondering which blog platform are you using for this website? I’m getting tired of WordPress because I’ve had issues with hackers and I’m looking at options for another platform. I would be awesome if you could point me in the direction of a good platform.

  27. situs togel's avatar situs togel says:

    Some truly nice and useful info on this internet site, also I think the design and style has got wonderful features.

  28. toto macau's avatar toto macau says:

    I have recently started a site, the information you provide on this website has helped me tremendously. Thanks for all of your time & work.

  29. Perfect piece of work you have done, this website is really cool with fantastic information.

  30. I really like your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz reply as I’m looking to design my own blog and would like to know where u got this from. thanks a lot

  31. I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme? Outstanding work!

  32. I loved up to you’ll receive performed right here. The comic strip is tasteful, your authored subject matter stylish. nevertheless, you command get got an shakiness over that you want be turning in the following. unwell without a doubt come further before once more as precisely the similar nearly very often within case you protect this increase.

  33. Valuable info. Lucky me I found your site by accident, and I’m shocked why this accident didn’t happened earlier! I bookmarked it.

  34. olxtoto's avatar olxtoto says:

    I was recommended this web site by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my trouble. You’re incredible! Thanks!

  35. Valuable information. Lucky me I found your site by accident, and I am shocked why this accident didn’t happened earlier! I bookmarked it.

  36. paito macau's avatar paito macau says:

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

  37. olxtoto's avatar olxtoto says:

    Good day! I know this is somewhat off topic but I was wondering which blog platform are you using for this website? I’m getting sick and tired of WordPress because I’ve had issues with hackers and I’m looking at alternatives for another platform. I would be great if you could point me in the direction of a good platform.

  38. slot pulsa's avatar slot pulsa says:

    I have been browsing online greater than three hours nowadays, but I never found any fascinating article like yours. It¦s pretty value enough for me. Personally, if all site owners and bloggers made good content as you probably did, the net shall be much more helpful than ever before.

  39. Some truly nice and utilitarian information on this website, besides I think the design holds superb features.

  40. situs slot's avatar situs slot says:

    Hello, i feel that i noticed you visited my blog thus i came to “return the favor”.I’m attempting to in finding issues to enhance my web site!I suppose its good enough to use a few of your ideas!!

  41. sportbootführerschein binnen und see, sportbootführerschein binnen prüfungsfragen, sportbootführerschein binnen kosten, sportbootführerschein binnen online, sporthochseeschifferschein kaufen, sportbootführerschein binnen berlin, sportbootführerschein binnen segel, sportbootführerschein kaufen, sportseeschifferschein kaufen erfahrungen, sportküstenschifferschein kaufen schwarz, sportbootführerschein see kaufen, sportbootführerschein binnen kaufen, sportbootführerschein see kaufen ohne prüfung, bootsführerschein kaufen, bootsführerschein kaufen polen, bootsführerschein kaufen erfahrungen, bootsführerschein online kaufen, bootsführerschein tschechien kaufen, SSS kaufen, SKS kaufen, SHS kaufen, führerschein kaufen,sportbootführerschein see, österreichischen führerschein kaufen legal, kaufen swiss registrierte führerschein, registrierten führerschein kaufen berlin, echten führerschein kaufen Köln, legal führerschein kaufen, echten deutschen führerschein kaufen, deutschen registrierten führerschein kaufen, osterreichischen-fuhrerschein-kaufen zürich, deutschen registrierten führerschein kaufen…987y6yh

  42. Some truly nice stuff on this web site, I love it.

  43. bandar togel's avatar bandar togel says:

    Please let me know if you’re looking for a article author for your weblog. You have some really great articles and I think I would be a good asset. If you ever want to take some of the load off, I’d absolutely love to write some articles for your blog in exchange for a link back to mine. Please blast me an email if interested. Regards!

  44. dolantoto88's avatar dolantoto88 says:

    It?¦s truly a great and useful piece of info. I?¦m satisfied that you simply shared this useful info with us. Please stay us up to date like this. Thanks for sharing.

  45. I’ve been surfing online greater than three hours as of late, but I never found any fascinating article like yours. It is beautiful worth sufficient for me. In my view, if all web owners and bloggers made good content material as you did, the internet will probably be a lot more helpful than ever before. “Truth is not determined by majority vote.” by Doug Gwyn.

  46. toto togel's avatar toto togel says:

    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.

  47. Great write-up, I am regular visitor of one?¦s website, maintain up the nice operate, and It is going to be a regular visitor for a long time.

  48. togel macau's avatar togel macau says:

    You are a very smart person!

  49. dolantoto's avatar dolantoto says:

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

  50. pg slot's avatar pg slot says:

    Thanks, I have recently been searching for information about this subject for ages and yours is the greatest I have came upon so far. But, what in regards to the conclusion? Are you certain about the supply?

Comments are closed.