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

fails to compile.

How can I pattern-match arrays?

theonlygusti
  • 11,032
  • 11
  • 64
  • 119

1 Answers1

3

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"
};
John Glenn
  • 1,469
  • 8
  • 13
  • 1
    And if one can choose to change the type of `x`, the code could be simplified by letting `(int, int) x = (1, 2);` ==> `var y = x switch { (1, 2) => "yea", _ => "nay" };`. – Astrid E. Jan 29 '22 at 07:03