Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is it possible to add two values to a conditional statement switch C#

the fact is that I need to check two variables with a large number of values
, I would like to write something like for a more convenient and clean code:

                switch (a, b)
                {
                    case 0, 0:
                        break;
                    case 0, 1:
                        break;
                    case 0, 2:
                        break;
                    case 0, 3:
                        break;
                    case 1, 0:
                        break;
                    case 1, 1:
                        break;
                    case 1, 2:
                        break;
                    case 1, 3:
                        break;
                }

But that’s the only way it works at the moment:

switch (a)
{
    case 0:
        switch (b)
        {
            case 0:
                break;
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
        }
        break;
    case 1:
        switch (b)
        {
            case 0:
                break;
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
        }
        break;
}

I expected that it would be possible to set the values as in the coordinate system

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You were thinking in the right direction, and all you had to do was add parentheses to the cases, then the compiler would understand that it was dealing with tuples:

switch (a, b)
{
    case (0, 0):
        break;
    case (0, 1):
        break;
    case (0, 2):
        break;
    case (0, 3):
        break;
    case (1, 0):
        break;
    case (1, 1):
        break;
    case (1, 2):
        break;
    case (1, 3):
        break;
}

If you need to assign something, then you can apply such a construction (starting from C#8):

var str = (a, b) switch
{
    (0, 0) => "A",
    (0, 1) => "B",
    (0, 2) => "C",
    (0, 3) => "D",
    (1, 0) => "E",
    (1, 1) => "F",
    (1, 2) => "G",
    (1, 3) => "H",
    _ => "?"
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading