Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this goto inside this switch work?

For this program:

class Program {     static void Main(string[] args)     {         var state = States.One;         switch (state)         {             case States.One:                 Console.WriteLine("One");                 break;             case States.Zero:                 goto case States.One;         }     } }  public enum States : ulong {     Zero = 0,     One = 1, } 

I got:

"A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type"

But state variable is enum type. The error disappears if I comment the goto case line.

I am using VS 2013. + .NET 4.5.1.

like image 615
Brans Ds Avatar asked May 12 '14 08:05

Brans Ds


People also ask

Can goto be used in switch?

A label is a valid C# identifier followed by colon. In this case, case and default statements of a Switch are labels thus they can be targets of a goto. However, the goto statement must be executed from within the switch. that is we cannot use the goto to jump into switch statement .

How to use goto in switch case in C?

The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the program control to a predefined label. The goto statment can be used to repeat some part of the code for a particular condition.

Can goto statement Go outside switch?

Yes, it does.

When should use goto?

When Should We Use the goto Statement? Goto statement is used for flow control in programs. As discussed above, it transfers the code execution of code from one part of the program to another. Hence, in any case, where you need to make a jump from one part of the code to another, you can use the goto statement.


2 Answers

This is known bug of the C# compiler when enum is typed as ulong and you use goto case at the same time. If you remove the ulong from enum, it compiles just fine. And because not many people run into this problem, they are not focusing on fixing it.

like image 75
Euphoric Avatar answered Oct 14 '22 14:10

Euphoric


Depending on your use case, this might also be an option for you:

switch (state) {     case States.Zero:     case States.One:         Console.WriteLine("One");         break; } 

This should be working according to an example here: http://msdn.microsoft.com/de-de/library/06tc147t.aspx

like image 35
T_D Avatar answered Oct 14 '22 15:10

T_D