How to use c# tuple value types in a switch statement

Viewed 14635

I'm using the new tuple value types in .net 4.7. In this example I am trying to make a switch statement for one or more cases of a tuple:

using System;
namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            (char letterA, char letterB) _test = ('A','B');
            Console.WriteLine($"Letter A: '{_test.letterA}', Letter B: '{_test.letterB}'");

            switch (_test)
            {
                case ('A', 'B'):
                    Console.WriteLine("Case ok.");
                    break;
            }

        }
    }
}

This does not compile unfortunately.

How do I take a tuple and make cases in a switch statement correctly?

7 Answers

Just a note for anyone who stumbled upon this question.

C# 8.0 introduces switch expressions which is really useful in this situation.

Now you can do something like this :

var test = ('A', 'B');
var result = test switch
{
    ('A', 'B') => "OK",
    ('A',   _) => "First part OK",
    (  _, 'B') => "Second part OK",
    _ => "Not OK",
};

Console.WriteLine(result);

Try in .NET fiddle

C# 7.3 introduces tuple equality which means your initial idea in the question is almost correct. You just need to capture the value you are comparing like this:

var _test = ('A','B');
switch (_test)
{
   case var t when t == ('A', 'B'):
   Console.WriteLine("Case ok.");
   break;
}

If one is ok and two is not ok in tuple then you can use the _ sign to discard one.

switch (_test)
{
    case ('A', 'B'):
        Console.WriteLine("Case A B ok.");
        break;
    case ('C', 'D'):
        Console.WriteLine("Case C D ok.");
        break;
    case ('A', _):
        Console.WriteLine("Case A ok.");
        break;
    case (_, 'B'):
        Console.WriteLine("Case B ok.");
        break;
    default:
        Console.WriteLine("Nothing ok.");
        break;
}

Update - C# 8.0

You can use the switch expression to proceed from the doc.

Console.WriteLine(_test switch
{
    ('A', 'B') => "Case A B ok.",
    ('C', 'D') => "Case C D ok.",
    ('A', _)   => "Case A ok.",
    (_, 'B')   => "Case A ok.",
    _          => "Nothing ok."
});
Related