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. His latest book, Building APIs with .NET, is now available wherever you buy your books. Liberty is a Senior SW Engineer for CNH and he was 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 Microsoft MVP.
This entry was posted in C#, Mini-Tutorial. Bookmark the permalink.

897 Responses to Modern C# Part 3 – Switch Expressions

  1. togel 4d's avatar togel 4d says:

    I genuinely treasure your piece of work, Great post.

  2. royalplay's avatar royalplay says:

    I have not checked in here for some time because I thought it was getting boring, but the last several posts are great quality so I guess I?娄ll add you back to my daily bloglist. You deserve it my friend 馃檪

  3. Generally I don’t read article on blogs, however I would like to say that this write-up very compelled me to check out and do it! Your writing taste has been surprised me. Thank you, quite great post.

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

  5. I have been browsing online more than 3 hours today, yet I by no means found any fascinating article like yours. It鈥檚 pretty price enough for me. Personally, if all webmasters and bloggers made good content as you did, the internet will likely be a lot more helpful than ever before.

  6. Simply a smiling visitant here to share the love (:, btw great design and style.

  7. Thanks for sharing excellent informations. Your web-site is so cool. I’m impressed by the details that you have on this site. It reveals how nicely you understand this subject. Bookmarked this website page, will come back for more articles. You, my friend, ROCK! I found simply the information I already searched everywhere and simply couldn’t come across. What a great site.

  8. Very interesting points you have noted, thankyou for posting.

  9. Great post, I conceive people should learn a lot from this weblog its rattling user genial.

  10. What i do not realize is in reality how you are now not really much more neatly-favored than you may be now. You are so intelligent. You understand therefore considerably in the case of this matter, made me for my part imagine it from so many varied angles. Its like men and women aren’t interested except it’s one thing to accomplish with Lady gaga! Your personal stuffs great. All the time take care of it up!

  11. I’ve been absent for a while, but now I remember why I used to love this website. Thanks , I will try and check back more often. How frequently you update your website?

  12. Sugaring effektive und moderne Haarentfernung in Berlin Die Epilation mit Zuckerpaste wird von unseren speziell daf眉r ausgebildeten Kosmetikerinnen / Depiladoras an allen K枚rperregionen durchgef眉hrt. Wir bieten diese effektive und moderne Behandlung sehr erfolgreich und schonend mit einem Maximum in der Hygiene der Anwendung an. Sugaring wird immer beliebter.

  13. bhai 88's avatar bhai 88 says:

    You have noted very interesting details! ps nice website . “Choose your friends carefully. Your enemies will choose you.” by Yassir Arafat.

  14. netizen303's avatar netizen303 says:

    Very interesting subject , appreciate it for putting up.

Leave a Reply

Your email address will not be published. Required fields are marked *