Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the current case in a switch statement?

Is is possible to determine which case is currently being evaluated? Something like this example code:

const int one = 1;
const int two = 2;

int current_num = 1;

switch (current_num){
       case one:
       case two:
           WriteLine(current_case) //outputs 'one'
           break;
}

I believe I could get tricky and use a dictionary or something to look up the current_num once I've begun to WriteLine, but there could be a built-in way to get the name of the current case currently being evaluated.

edit: Short answer, it's not possible. Check out JonSkeet's answer for a plausible alternative.

like image 566
TankorSmash Avatar asked Nov 20 '25 12:11

TankorSmash


1 Answers

It's not really clear what you're trying to do, but I suspect you'd be better off with an enum:

enum Foo {
    One = 1,
    Two = 2,
    Three = 3
}

...

int someValue = 2;
Foo foo = (Foo) someValue;
Console.WriteLine(foo); // Two

You can still use this within a case statement:

switch (foo) {
    case Foo.One:
    case Foo.Two:
        Console.WriteLine(foo); // One or Two, depending on foo
        break;
    default:
        Console.WriteLine("Not One or Two");
}
like image 87
Jon Skeet Avatar answered Nov 23 '25 03:11

Jon Skeet