Multi-variable switch statement in C#

后端 未结 12 511
-上瘾入骨i
-上瘾入骨i 2020-12-15 16:54

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

switch (intVal1, strVal2, boolVal3)
{
   case 1, \"hello\", false:
            


        
12条回答
  •  难免孤独
    2020-12-15 17:56

    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"
        };
    

提交回复
热议问题