jharr100
jharr100

Reputation: 1469

C# 7 Pattern Match with a tuple

Is it possible to use tuples with pattern matching in switch statements using c# 7 like so:

switch (parameter)
{
   case ((object, object)) tObj when tObj.Item1 == "ABC":
        break;
}

I get an error that says tObj does not exist in the current context.

I have tried this as well:

switch (parameter)
{
   case (object, object) tObj when tObj.Item1 == "ABC":
        break;
}

This works fine:

switch (parameter)
{
   case MachineModel model when model.Id == "123":
        break;
}

Upvotes: 14

Views: 5672

Answers (1)

DavidG
DavidG

Reputation: 118977

Remember that C#7 tuples are just syntactic sugar, so (object, object) is really just System.ValueTuple<object, object>.

I guess that the dev team didn't take this particular situation into account for the new syntax for tuples, but you can do this:

switch (parameter)
{
    case System.ValueTuple<object, object> tObj when tObj.Item1 == "x":
        break;
}

Also, since the "var pattern" will match anything and respect the type, the above can be simplified to:

switch (parameter)
{
    case var tObj when tObj.Item1 == "x":
        break;
}

Upvotes: 20

Related Questions