Skip to content

Switch tuple pattern C# 8.0code reductionreadability

Match against multiple values simultaneously using tuple patterns.

Pattern matching multiple related values required nested if statements or complex boolean logic. This was particularly cumbersome when the logic depended on combinations of multiple variables.

C# 8.0 introduces tuple patterns, allowing you to match against multiple values simultaneously in a single pattern. This is especially powerful with switch expressions for writing clear, concise logic based on combinations of values.

Code

C#
public string GetQuadrant(int x, int y) => (x, y) switch
{
    (0, 0) => "Origin",
    (> 0, > 0) => "Quadrant I",
    (< 0, > 0) => "Quadrant II",
    (< 0, < 0) => "Quadrant III",
    (> 0, < 0) => "Quadrant IV",
    (0, _) => "On X-axis",
    (_, 0) => "On Y-axis"
};

public string RockPaperScissors(string player1, string player2) => (player1, player2) switch
{
    ("rock", "scissors") or ("scissors", "paper") or ("paper", "rock") => "Player 1 wins",
    ("scissors", "rock") or ("paper", "scissors") or ("rock", "paper") => "Player 2 wins",
    _ => "Draw"
};
C#
public string GetQuadrant(int x, int y)
{
    if (x == 0 && y == 0)
        return "Origin";
    if (x > 0 && y > 0)
        return "Quadrant I";
    if (x < 0 && y > 0)
        return "Quadrant II";
    if (x < 0 && y < 0)
        return "Quadrant III";
    if (x > 0 && y < 0)
        return "Quadrant IV";
    if (x == 0)
        return "On X-axis";
    return "On Y-axis";
}

public string RockPaperScissors(string player1, string player2)
{
    if ((player1 == "rock" && player2 == "scissors") ||
        (player1 == "scissors" && player2 == "paper") ||
        (player1 == "paper" && player2 == "rock"))
        return "Player 1 wins";
    if ((player1 == "scissors" && player2 == "rock") ||
        (player1 == "paper" && player2 == "scissors") ||
        (player1 == "rock" && player2 == "paper"))
        return "Player 2 wins";
    return "Draw";
}

Notes

  • Create a tuple of values to match against: (value1, value2) switch { ... }
  • Each arm matches against a tuple pattern: (pattern1, pattern2) => result
  • Use _ as a discard pattern to match any value for that position
  • Supports all pattern types including relational patterns, constant patterns, and type patterns
  • Can combine with the or pattern to match multiple tuple combinations
  • Particularly useful for state machines, game logic, or any multi-variable decision logic
  • Order matters - the first matching pattern wins

More information