using System; class Program { static string Describe((int, (int, int)) data) => data switch { (0, (0, 0)) => "All zeros", (var x, (var y, var z)) when x == y && y == z => "All equal", (var x, (_, var z)) when x > z => "First greater than last", _ => "Other" }; static void Main() { Console.WriteLine(Describe((0, (0, 0)))); Console.WriteLine(Describe((3, (3, 3)))); Console.WriteLine(Describe((5, (1, 2)))); Console.WriteLine(Describe((1, (2, 3)))); } }
The method Describe uses recursive pattern matching on a tuple containing an int and another tuple of two ints.
1. (0, (0, 0)) matches the first pattern exactly, so prints "All zeros".
2. (3, (3, 3)) matches the second pattern where all three values are equal, so prints "All equal".
3. (5, (1, 2)) matches the third pattern because 5 > 2, so prints "First greater than last".
4. (1, (2, 3)) matches none of the first three patterns, so prints "Other".
result after execution?using System; using System.Collections.Generic; class Program { static int SumList(List<int> list) => list switch { [] => 0, [var head, .. var tail] => head + SumList(tail) }; static void Main() { var numbers = new List<int> {1, 2, 3}; var result = SumList(numbers); Console.WriteLine(result); } }
The method SumList uses recursive pattern matching on a list.
It matches an empty list [] returning 0.
Otherwise, it matches a list with a head and tail, sums the head with the recursive sum of the tail.
For the list [1, 2, 3], the sum is 1 + 2 + 3 = 6.
using System; class Program { static int Factorial(int n) => n switch { 0 => 1, > 0 => n * Factorial(n - 1), _ => throw new ArgumentException("Negative input") }; static void Main() { Console.WriteLine(Factorial(-1)); } }
The method Factorial uses pattern matching on n.
For n == 0, returns 1.
For n > 0, recursively calculates factorial.
For any other value (negative), it throws ArgumentException with message "Negative input".
Calling Factorial(-1) triggers this exception.
Option A uses var (h, t) which is invalid syntax in C# pattern matching.
Correct tuple patterns use parentheses with var for each element, like (var h, var t).
Options B, C, and D use valid tuple patterns.
using System; class Program { static int Depth(object obj) => obj switch { (var l, var r) => 1 + Math.Max(Depth(l), Depth(r)), _ => 0 }; static void Main() { var nested = ((1, (2, 3)), (4, 5)); Console.WriteLine(Depth(nested)); } }
The method Depth uses recursive positional pattern matching on 2-tuples.
If yes, it adds 1 plus the maximum depth of its two elements.
The nested tuple ((1, (2, 3)), (4, 5)) has depth 3:
- Level 1: outer tuple
- Level 2: first item is a tuple (1, (2, 3))
- Level 3: inside that, second item is (2, 3)
The right branch (4, 5) reaches depth 2, so max is 3.