Friday, June 2, 2023

Switch syntax has a new look in C# 8


     The switch is a very useful syntax to use if you have many if-else statements. The switch can easily combine these statements and make your code more readable. Before the C# 8 update, the switch looked like in the following example.

  public enum role
  {
        Guest,
        Member,
        SuperUser,
        Admin,
        Owner
  }
    
  switch (userrole)
  {
      case role.Guest:
          Console.WriteLine("Guest");
          break;
      case role.Member:
          Console.WriteLine("Member");
          break;
      case role.SuperUser:
          Console.WriteLine("SuperUser");
          break;
      case role.Admin:
          Console.WriteLine("Admin");
          break;
      case role.Owner:
          Console.WriteLine("Owner");
          break;
  }
  
  

It works great but the break and the case syntaxes are getting duplicated, new switch syntax gets rid of the case, and the break statements. Here how this example looks like using the new switch syntax.

    public static string HandleUserrole(roles userrole) => 
        userrole switch
    {
        roles.Guest => "Guest",
        roles.Member => "Member",
        roles.SuperUser => "SuperUser",
        roles.Admin => "Admin",
        roles.Owner => "Owner",
        _ => "Unknown"
    };
    

You might say these two examples are not doing the same thing because the new switch can not return void anymore. You can still use the older version of the switch if you don't want to return anything by using the switch. 

No comments:

Post a Comment