Combine return and switch

Neir0 picture Neir0 · Jul 26, 2010 · Viewed 97.6k times · Source

How can I combine return and switch case statements?

I want something like

return switch(a)
       {
          case 1:"lalala"
          case 2:"blalbla"
          case 3:"lolollo"
          default:"default" 
       };

I know about this solution

switch(a)
{
    case 1: return "lalala";
    case 2: return "blalbla";
    case 3: return "lolollo";
    default: return "default";
}

But I want to only use the return operator.

Answer

Daniel Z. picture Daniel Z. · Sep 6, 2019

Actually this is possible using switch expressions starting with C# 8.

return a switch
    {
        1 => "lalala",
        2 => "blalbla",
        3 => "lolollo",
        _ => "default"
    };

Switch Expressions

There are several syntax improvements here:

  • The variable comes before the switch keyword. The different order makes it visually easy to distinguish the switch expression from the switch statement.
  • The case and : elements are replaced with =>. It's more concise and intuitive.
  • The default case is replaced with a _ discard.
  • The bodies are expressions, not statements.

For more information and examples check the Microsoft's C# 8 Whats New.