Search code examples
c#goto

Why am I getting a syntax error when I try to create a code label in C# (for goto)?


Consider the following:

class abc {
    public void foobar() {
        while(true) {
            while(true) {
                goto mylabel;
            }
        }
        mylabel:
    }
}

I get a syntax error on the : of mylabel that says:

Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

Am I losing my mind here? What on earth am I doing wrong? I have googled up and down and it seems my syntax is correct.


Solution

  • After the label, you need a statement. A closing } isn't a statement, it is ending a block of code. You can use the empty statement (;) here:

    mylabel: ;
    

    The linked page even states:

    Also, an empty statement can be used to declare a label just before the closing "}" of a block: