Search code examples
c#pattern-matchingswitch-expression

C# Pattern match arrays


var x = new int[] { 1, 2 };
var y = x switch {
  { 1, 2 } => "yea",
  _ => "nay"
};

fails to compile.

How can I pattern-match arrays?


Solution

  • You have to expand the elements of the array yourself like so

    var x = new int[] { 1, 2 };
    var y = (x[0], x[1]) switch {
      (1, 2) => "yea",
      _ => "nay"
    };