2

I am trying to use a type pattern in C# 7 against a tuple type:

var lst = new List<object>();
lst.Add("foo");
lst.Add(("bar","baz"));

foreach (var item in lst) {
    switch (item) { 
        case string s:
            break;
        case (string, string) t: //Compiler error here
            break;
    }
}

but the compiler gives me the following error:

Invalid expression term 'string' A constant value is expected

How can I resolve this?


N.B. I know I can use:

case ValueTuple<string,string> t:

but I am wondering if there is a better syntax.

Julien Couvreur
  • 4,473
  • 1
  • 30
  • 40
Zev Spitz
  • 13,950
  • 6
  • 64
  • 136

2 Answers2

4

Just use case ValueTuple<string, string> t:.

You just added the same solution to your question while I posted this answer. Well, you'll have to stick with this solution until they add compiler support for the case (,): syntax (wouldn't wait for that since this is an edge case).

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
1

There are different sorts of patterns which were not implemented in C# 7.0, but are tracked in the patterns proposal, including recursive and positional patterns that you describe. Some of those are candidate for later 7.x point releases.

Julien Couvreur
  • 4,473
  • 1
  • 30
  • 40