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. pro solution's avatar pro solution says:

    Nice read. Thumbs up! I used to study this stuff back in school. Good job on this article!

  2. Sinu Deban's avatar Sinu Deban says:

    Nice blog. Could someone with little experience do it, and add updates without messing it up? Good information on here, very informative.

  3. black penis's avatar black penis says:

    Just what I’m trying to find.

  4. No selling's avatar No selling says:

    Nice read. Great read. Interesting content. It’s like you wrote the book on it or something.

  5. Thanks for another informative website. Where else could I get that kind of info written in such a perfect way? I have a project that I am just now working on, and I’ve been on the look out for such information.

  6. Money back's avatar Money back says:

    This is an excellent, an eye-opener for sure! Your article has proven useful to me. Thanks for writing this. Thanks for writing this. The people at best price are a rip off I truly appreciate this post. Nice read. Your article has proven useful to me. Your article couldn’t be written any better! I have been looking everywhere for this! Some nice points there. Some nice points there. Great read. I have been looking everywhere for this! You appear to know a lot about this. Thanks for writing this. This is an excellent, an eye-opener for sure!

  7. web service's avatar web service says:

    You’ve made my day! Thx again. I truly love your blogs. I truly appreciate this post. Nice read.

  8. bachvideoai's avatar bachvideoai says:

    I really appreciate you distinguishing between the traditional switch statement and the newer switch expression right away, as that is a common point of confusion for developers making the jump. It’s interesting to see how the syntax shifts from a procedural block of statements to a declarative pattern matching logic that feels much more aligned with modern C# capabilities. Looking forward to the rest of this series as you explore deeper pattern matching techniques.

  9. Great breakdown of switch expressions, Jesse. I’ve been using them in my recent projects and the concise syntax really cleans up repetitive if-else chains. One thing I’m still getting used to is the discard pattern—do you find it replaces most null checks in practice, or do you still lean on traditional guards?

  10. Free Valium's avatar Free Valium says:

    It’s like you wrote the book on it or something. This is an excellent, an eye-opener for sure! You are a very persuasive writer. It’s like you read my thoughts! check now. Great post! Your article has proven useful to me. It’s like you read my thoughts! You’ve made my day! Thx again. This is an excellent, an eye-opener for sure! You’ve made my day! Thx again. You appear to know a lot about this. This is a topic that is near to my heart… Best wishes! Where are your contact details though? Great post! I enjoyed reading this. I have been looking everywhere for this! Good job on this article!

  11. wanimage's avatar wanimage says:

    The comparison between traditional switch statements and the more concise switch expressions really highlights the power of pattern matching in modern C#. I particularly appreciate how you break down the syntax differences, as it clarifies why the expression form is often preferred for cleaner code. Shifting from imperative blocks to pattern-based returns definitely makes logic like your ‘GetDay’ example much more readable.

  12. I like what you guys are up too. Such smart work and reporting! Keep up the superb works guys I have incorporated you guys to my blogroll. I think it’ll improve the value of my site 🙂

  13. SCAM's avatar SCAM says:

    Nice post. I learn something new and challenging on blogs I stumbleupon on a daily basis.

    It will always be exciting to read through articles from other

    authors and practice a little something from their websites.

  14. Hi 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 greatly appreciated!

  15. GARASISLOT's avatar GARASISLOT says:

    Hello very nice website!! Guy .. Beautiful ..

    Wonderful .. I’ll bookmark your site and take the feeds additionally?

    I am happy to search out so many useful info here in the submit, we want work out more strategies on this regard, thank you for sharing.

    . . . . .

  16. tgwsproxy's avatar tgwsproxy says:

    Jesse, your distinction between the traditional switch statement and the modern switch expression really clarifies why pattern matching feels so much more powerful. I particularly like how you highlight that switch expressions return a value directly, which naturally encourages more concise and functional-style code. Looking forward to seeing how this expands into the other pattern matching techniques in your upcoming posts.

  17. Your explanation of the distinct syntax and expressive power of switch expressions compared to traditional statements is spot on, especially for handling pattern matching cases. It is great to see this transition from simple case labels to more readable code structures that reduce the boilerplate often seen in switch statements. Looking forward to the rest of the series as you dive deeper into these patterns.

  18. Pingback: HUAYHENG789

  19. I came across this while looking for something completely different, and I ended up finishing most of it. it helped me see things differently in a way that actually makes sense. I’ll probably revisit this again.

  20. Funny enough, It explained things better than most sites I’ve seen.

  21. So, This popped up while I was checking something else, and I actually read it fully. it made things less confusing which made it more readable. I might come back and read more later.

  22. MorseCodeGen's avatar MorseCodeGen says:

    This series is a fantastic breakdown of pattern matching, and your comparison really highlights why switch expressions are so much cleaner than traditional statements for simple logic like mapping day numbers. I’m particularly looking forward to seeing how you expand on the pattern matching capabilities in the follow-up posts, as it seems like a huge leap for writeability in C#.

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

  24. Thanks for breaking down switch expressions in such a clear way—especially the distinction between switch statements and expressions. I found the pattern-matching example really helpful in understanding how switch expressions can make code more concise and readable. It’s a small change that can lead to big improvements in maintainability.

  25. Thanks for breaking down switch expressions in such a clear way—especially the distinction between switch statements and expressions. I found the pattern-matching example really helpful in understanding how switch expressions can make code more concise and readable. It’s a small change that can lead to big improvements in maintainability.

  26. Find the best ragnarok online private server for you. RateMyRagnarok ranks ragnarok private servers with VPN-protected reviews so ratings stay honest. Browse 40,000+ items, monsters, maps, and skills in our complete ragnarok online database. Compare ragnarok servers side by side, read real player reviews, and discover new ragnarok online servers before anyone else. Whether you’re looking for a ragnarok origin private server, a classic ro private server, or the top ragnarok private servers in 2026, RMR has you covered. List your ragnarok server for free and let the community decide. The RO hub built by players, for players.

  27. AI Dance's avatar AI Dance says:

    Appreciate the clarity here. Technical breakdowns like this are useful, especially for creators and developers exploring adjacent tools such as AI Dance.

  28. Pretty component of content. I simply stumbled upon your website and in accession capital to say that I acquire actually enjoyed account your weblog posts. Any way I?ll be subscribing in your augment or even I achievement you access consistently rapidly.

  29. Thanks for breaking down switch expressions in such a clear way—especially the distinction between switch statements and expressions. I found your example with the Direction enum helpful in understanding how pattern matching can make code more concise and readable. It’s a small change, but one that really improves maintainability when dealing with multiple conditions.

  30. Duct Tape AI's avatar Duct Tape AI says:

    Really enjoyed this post on Modern C# Part 3 – Switch Expressions | Jesse Liberty. The practical detail is what stood out to me. I often use Duct Tape AI for fast image mockups and simple text-on-image experiments, and writing with this much clarity tends to translate especially well into visual work.

  31. Bonus's avatar Bonus says:

    As I site possessor I believe the content material here is rattling excellent , appreciate it for your hard work. You should keep it up forever! Good Luck.

  32. Thanks for breaking down switch expressions in such a clear way—especially the distinction between switch statements and expressions. I found the example with the Direction enum helpful in understanding how pattern matching can make code more concise and readable. It’s a nice evolution from traditional switch logic, and I’m excited to explore more patterns in upcoming posts.

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

  34. I am impressed with this site, really I am a big fan .

  35. try2fa's avatar try2fa says:

    Thanks for breaking down switch expressions in a practical way—especially the contrast with traditional switch statements helped clarify when it might be better to use the expression form. I’m particularly interested in exploring how pattern matching ties into this, as you mentioned in your intro. The example with the Direction enum is a great starting point for understanding the syntax and flow.

  36. what happens if you take steroids and don’t workout

    References:
    https://monjournal.top/

  37. how long between steroid cycles

    References:
    eskisehiruroloji.com

Comments are closed.