Search code examples
c#.netswitch-statementlogicswitch-expression

Multi-variable switch statement in C#


I would like use a switch statement which takes several variables and looks like this:

switch (intVal1, strVal2, boolVal3)
{
   case 1, "hello", false:
      break;
   case 2, "world", false:
      break;
   case 2, "hello", false:

   etc ....
}

Is there any way to do something like this in C#? (I do not want to use nested switch statements for obvious reasons).

The question was answered by .net dev team by implementing of exactly this fearture: Multi-variable switch statement in C#


Solution

  • Yes. It's supported as of .NET 4.7 and C# 8. The syntax is nearly what you mentioned, but with some parenthesis (see tuple patterns).

    switch ((intVal1, strVal2, boolVal3))
    {
        case (1, "hello", false):
            break;
        case (2, "world", false):
            break;
        case (2, "hello", false):
            break;
    }
    

    If you want to switch and return a value there's a switch "expression syntax". Here is an example; note the use of _ for the default case:

    string result = (intVal1, strVal2, boolVal3) switch
    {
        (1, "hello", false) => "Combination1",
        (2, "world", false) => "Combination2",
        (2, "hello", false) => "Combination3",
        _ => "Default"
    };
    

    Here is a more illustrative example (a rock, paper, scissors game) from the MSDN article linked above:

    public static string RockPaperScissors(string first, string second)
        => (first, second) switch
        {
            ("rock", "paper") => "rock is covered by paper. Paper wins.",
            ("rock", "scissors") => "rock breaks scissors. Rock wins.",
            ("paper", "rock") => "paper covers rock. Paper wins.",
            ("paper", "scissors") => "paper is cut by scissors. Scissors wins.",
            ("scissors", "rock") => "scissors is broken by rock. Rock wins.",
            ("scissors", "paper") => "scissors cuts paper. Scissors wins.",
            (_, _) => "tie"
        };