0Pricing
C# Academy · Lesson

List and Tuple Patterns

Destructure collections.

Tuple Patterns

A tuple pattern matches several values at once by wrapping them in parentheses. Each position is matched by its own sub-pattern.

This is ideal for decisions that depend on multiple inputs, like a small state machine or a rock-paper-scissors judge, all in one switch.

int x = 0, y = 5;
string quadrant = (x, y) switch
{
    (0, 0) => "origin",
    (0, _) => "y-axis",
    (_, 0) => "x-axis",
    _ => "plane"
};
System.Console.WriteLine(quadrant);

A Runnable Tuple Switch

Tuple patterns make decision tables readable. Here two booleans pick an action.

Each arm lists a tuple pattern, and the discard _ in a position means that slot can be anything. The final _ arm covers the rest.

using System;

class Program {
    static string Move(bool fwd, bool turn) => (fwd, turn) switch {
        (true, false) => "straight",
        (true, true) => "curve",
        (false, true) => "spin",
        _ => "stop"
    };
    static void Main() => Console.WriteLine(Move(true, true));
}

All lessons in this course

  1. switch Expressions
  2. Type and Property Patterns
  3. Relational and Logical Patterns
  4. List and Tuple Patterns
← Back to C# Academy