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

    What¦s Going down i am new to this, I stumbled upon this I have discovered It absolutely useful and it has helped me out loads. I hope to give a contribution & assist other users like its aided me. Good job.

  2. kaki268's avatar kaki268 says:

    Hi! I’ve been following your site for a while now and finally got the courage to go ahead and give you a shout out from Huffman Tx! Just wanted to mention keep up the fantastic work!

  3. Hi my family member! I want to say that this article is awesome, great written and come with almost all significant infos. I¦d like to see extra posts like this .

  4. I?¦m now not sure where you’re getting your information, but great topic. I must spend some time studying much more or understanding more. Thanks for wonderful information I was looking for this info for my mission.

  5. kaki268's avatar kaki268 says:

    I have been reading out a few of your articles and i can claim pretty good stuff. I will definitely bookmark your website.

  6. lgopro99's avatar lgopro99 says:

    There is noticeably a bundle to know about this. I assume you made sure good points in options also.

  7. hello!,I really like your writing very much! share we keep up a correspondence more about your post on AOL? I need a specialist in this space to unravel my problem. May be that’s you! Looking forward to look you.

  8. Adorei este site. Para saber mais detalhes acesse nosso site e descubra mais. Todas as informações contidas são conteúdos relevantes e únicos. Tudo que você precisa saber está está lá.

  9. Hello! I just want to give an enormous thumbs up for the nice info you have right here on this post. I will be coming back to your blog for more soon.

  10. After all, what a great site and informative posts, I will upload inbound link – bookmark this web site? Regards, Reader.

  11. basket168's avatar basket168 says:

    Woah! I’m really enjoying the template/theme of this blog. It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between user friendliness and visual appeal. I must say you’ve done a superb job with this. Also, the blog loads very fast for me on Safari. Superb Blog!

  12. olxtoto's avatar olxtoto says:

    Woh I like your articles, bookmarked! .

  13. tlovertonet's avatar tlovertonet says:

    Sweet blog! I found it while surfing around on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Many thanks

  14. Pingback: รับจด อย

  15. Pingback: จำหน่าย พัดลมอุตสาหกรรม

  16. Can you write more about it? Your articles are always helpful to me. Thank you! http://www.kayswell.com

  17. Thanks for posting. I really enjoyed reading it, especially because it addressed my problem. http://www.ifashionstyles.com It helped me a lot and I hope it will help others too.

  18. Pingback: เกียรติบัตรฟรี

  19. Pingback: Online Pharmacy Denver

  20. Pingback: fear of god essentials

  21. Pingback: tga168win

  22. Pingback: ตู้ล่าม

  23. Pingback: pg168

  24. Pingback: situs toto

  25. extremely grateful for you posting this article immaculate post! Need a book cover? Take a peek at https://inkstorydesigns.com Use code FIRST30 to get 30 OFF your first book cover design! 3–5 Day SPEEDY Delivery | Upload-ready files included for publishing | & FREE 3D Book Renderings – Get a custom book cover design now for ONLY $349!

  26. Good web site! I truly love how it is easy on my eyes and the data are well written. http://www.kayswell.com I am wondering how I could be notified whenever a new post has been made. I’ve subscribed to your RSS which must do the trick! Have a nice day!

  27. Pingback: เว็บตรงฝากถอนง่าย

  28. Pingback: โคมไฟ

  29. I loved as much as you will receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get got an shakiness over that you wish be delivering the following. unwell unquestionably come further formerly again since exactly the same nearly a lot often inside case you shield this hike.

  30. Pingback: ufa11k

  31. Pingback: เครื่องเป่าแอลกอฮอล์

  32. Pingback: clothing manufacturer

  33. Pingback: จัดงานศพครบวงจร

  34. Pingback: check

  35. Pingback: royal joker

  36. Pingback: เน็ต บ้าน ais

  37. I抎 have to examine with you here. Which is not one thing I often do! I enjoy reading a submit that will make individuals think. Additionally, thanks for allowing me to comment!

  38. tlovertonet's avatar tlovertonet says:

    Whats up this is somewhat of off topic but I was wanting to know 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!

  39. Pingback: pinco apk

  40. Pingback: EV Charger

  41. Pingback: book fo ra

  42. It’s perfect time to make a few plans for the long run and it’s time to be happy. I’ve read this post and if I could I desire to suggest you some fascinating issues or suggestions. Maybe you could write next articles referring to this article. I want to learn more issues about it!

  43. Pingback: ลำดับของพรีเมียร์ลีก

  44. Pingback: Fiber-Coupled Laser Sources

  45. Hi there, You have performed a fantastic job. I will definitely digg it and personally suggest to my friends. I am confident they will be benefited from this web site.

  46. Pingback: My Homepage

  47. vzEjl's avatar vzEjl says:

    863560 70329Hello! I could have sworn Ive been to this weblog before but soon after browsing by way of some with the post I realized it is new to me. Anyways, Im surely pleased I identified it and Ill be book-marking and checking back regularly! 594615

  48. Have you ever considered about adding a little bit more than just your articles? I mean, what you say is important and everything. But think about if you added some great visuals or videos to give your posts more, “pop”! Your content is excellent but with pics and videos, this blog could undeniably be one of the greatest in its field. Amazing blog!

  49. I was looking at some of your content on this internet site and I conceive this site is very informative! Keep on putting up.

Comments are closed.