in Dot Net by
Q:
Tuple patterns in C#

1 Answer

0 votes
by

Some algorithms depend on multiple inputs. Tuple patterns allow you to switch based on multiple values expressed as a tuple. The following code shows a switch expression for the game rock, paper, scissors:

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"

    };

Related questions

0 votes
asked Dec 8, 2019 in Dot Net by Sinaya
0 votes
0 votes
0 votes
asked Dec 8, 2019 in Dot Net by Sinaya
0 votes
asked Dec 8, 2019 in Dot Net by Sinaya
  • c#-nullable
  • nullable-in-c#
0 votes
0 votes
asked Dec 8, 2019 in Dot Net by Sinaya
0 votes
0 votes
asked Dec 8, 2019 in Dot Net by Sinaya
...