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. anabolic steroids cycles

    References:
    doc.adminforge.de

  2. excellent points altogether, you just gained a brand new reader. What would you recommend in regards to your post that you made a few days ago? Any positive?

  3. Howdy this is kinda of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding know-how so I wanted to get advice from someone with experience. Any help would be greatly appreciated!

  4. best steroid cycle for lean mass

    References:
    elearnportal.science

  5. imoodle.win's avatar imoodle.win says:

    what happens if you side with the institute

    References:
    imoodle.win

  6. ripped muscle x at gnc

    References:
    md.swk-web.com

  7. Thanks for your suggestions. One thing I’ve got noticed is the fact banks in addition to financial institutions are aware of the spending behavior of consumers and as well understand that most people max outside their own credit cards around the holidays. They properly take advantage of that fact and then start flooding a person’s inbox and also snail-mail box using hundreds of no-interest APR credit cards offers shortly when the holiday season ends. Knowing that if you’re like 98 of the American open public, you’ll get at the possiblity to consolidate credit debt and move balances towards 0 APR credit cards.

  8. Thank you for every other wonderful post. Where else may anybody get that kind of info in such an ideal way of writing? I have a presentation next week, and I am on the look for such info.

  9. Great ? I should certainly pronounce, impressed with your website. I had no trouble navigating through all tabs and related info ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or anything, website theme . a tones way for your customer to communicate. Nice task..

  10. I read this piece of writing completely on the topic of the comparison of newest and previous technologies, it’s awesome article.

  11. I believe that avoiding refined foods will be the first step to lose weight. They will often taste fine, but processed foods contain very little vitamins and minerals, making you take in more in order to have enough strength to get through the day. When you are constantly ingesting these foods, switching to whole grains and other complex carbohydrates will help you have more energy while having less. Good blog post.

  12. jsonformat's avatar jsonformat says:

    I’ve definitely gone through that same mental shift while adjusting to pattern matching, as it feels so different from the classic procedural style. Do you find that the conciseness of switch expressions ever creates readability issues when the logic patterns become particularly complex?

  13. you have got an incredible blog right here! would you wish to make some invite posts on my blog?

  14. I have not checked in here for a while since I thought it was getting boring, but the last few posts are great quality so I guess I?ll add you back to my daily bloglist. You deserve it my friend 🙂

  15. 寻秦记's avatar 寻秦记 says:

    Live football scores with detailed match statistics, possession, shots, and player ratings

  16. Hey very cool blog!! Man .. Excellent .. Amazing .. I’ll bookmark your site and take the feeds also…I am happy to find a lot of useful information here in the post, we need develop more strategies in this regard, thanks for sharing. . . . . .

  17. Hey, you used to write magnificent, but the last few posts have been kinda boring?K I miss your great writings. Past few posts are just a little bit out of track! come on!

  18. scalp brush's avatar scalp brush says:

    Thank you for some other great post. Where else could anyone get that kind of information in such an ideal approach of writing? I have a presentation subsequent week, and I am on the look for such info.

  19. There are some attention-grabbing time limits on this article however I don?t know if I see all of them middle to heart. There is some validity however I’ll take maintain opinion till I look into it further. Good article , thanks and we would like extra! Added to FeedBurner as nicely

  20. Great breakdown, Jesse. I initially leaned on standard switch statements out of habit, but once you get comfortable with the expression syntax, it’s amazing how much cleaner and more readable the code becomes. Looking forward to the rest of the series on pattern matching!

  21. MorseCodeGen's avatar MorseCodeGen says:

    The shift from imperative switch statements to expressions is a total game-changer for code readability. I’m curious if you find that this style changes how you approach error handling in your projects, especially when it comes to covering all potential cases?

  22. trc20 scan's avatar trc20 scan says:

    Hey this is kinda of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding skills so I wanted to get advice from someone with experience. Any help would be greatly appreciated!

  23. gptimg2img's avatar gptimg2img says:

    Thanks for breaking down switch expressions—they really do feel more intuitive once you get used to the pattern-matching syntax. I especially appreciated how you highlighted the difference between switch statements and expressions, since that distinction can trip up a lot of developers. It’s also great to see the example with the Direction enum, as it makes the concept much clearer in practice.

  24. bayvip 2022's avatar bayvip 2022 says:

    Remember ‘bayvip 2022’? Still a classic! This link is the place to get it. Good times ahead! bayvip 2022

  25. The Yolo betting app is pretty solid. A lot of great functionality and great performance. It’s definitely worth it. Learn more about this site yolo betting app

  26. Alright, gamers! Help a brother out. Searching for the Tiranga download APK. Need that sweet, sweet offline play. Know a legit place? Get yours now! tiranga download apk

  27. Banana's avatar Banana says:

    Thanks for breaking down switch expressions—they really do feel more intuitive once you get used to the pattern-matching syntax. I especially appreciated how you highlighted the difference between switch statements and expressions, since that distinction can trip up a lot of developers. It’s a small change in approach but makes code much cleaner, especially when dealing with complex conditions.

  28. Howdy would you mind stating which blog platform you’re using? I’m planning to start my own blog soon but I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something unique. P.S Sorry for getting off-topic but I had to ask!

  29. Thanks for the detailed breakdown of switch expressions. The examples really helped clarify the syntax. Looking forward to more C# content!

  30. Tech Blogger's avatar Tech Blogger says:

    Great article about switch expressions in C#! Very helpful explanation.

  31. The interface is low fees, and I enjoy using the mobile app here.

  32. I trust this platform — withdrawals are robust security and reliable. Perfect for both new and experienced traders.

  33. Hey there, I think your blog might be having browser compatibility issues. When I look at your blog in Chrome, 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, terrific blog!

  34. Simply desire to say your article is as astonishing.
    The clarity to your post is just great and that i could
    assume you are knowledgeable in this subject.
    Well with your permission let me to snatch your RSS feed to keep up to date with drawing close
    post. Thank you 1,000,000 and please keep up the rewarding work.

  35. Hey there just wanted to give you a quick heads up and let you know a few
    of the pictures aren’t loading properly. I’m not sure
    why but I think its a linking issue. I’ve tried
    it in two different web browsers and both show the same outcome.

  36. 捕风追影在线平台,專為海外華人設計,提供高清視頻和直播服務。

  37. Outstanding post, I think website owners should larn a lot from this web blog its rattling user pleasant.

  38. It is in point of fact a nice and useful piece of info. I am happy that you just shared this useful information with us. Please keep us informed like this. Thank you for sharing.

  39. Hey this is kinda of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding know-how so I wanted to get advice from someone with experience. Any help would be enormously appreciated!

  40. Great post. I am facing a couple of these problems.

  41. Pretty great post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I will be subscribing in your feed and I am hoping you write again very soon!

  42. As I web-site possessor I believe the content material here is rattling magnificent , appreciate it for your efforts. You should keep it up forever! Good Luck.

  43. It’s a pity you don’t have a donate button! I’d certainly donate to this fantastic blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to brand new updates and will share this site with my Facebook group. Chat soon!

Comments are closed.