Arno# - The cutting edge of developer waffle

Some random thoughts on software development

goto: evil incarnate, or handy keyword?

What is it?

The goto statement is generally looked down on by experienced developers, as it all too easily encourages the writing of near-unreadable code. The goto command jumps execution to another point in the code, specified by a label.

Which C# version supports it?

All versions of C# support it.

Why use it?

Ideally you should never use goto. However, it does have a use that is generally regarded as a special case exception to this rule: escaping from a deeply nested loop. The reason why you might need to do this is due to a deficiency in the C# language: it doesn’t support break to label. Ideally, if you had a case where you wanted to abort a multi-dimensional loop, you might expect be able to put something like:

OuterLoop: for (int n=0; n<10; n++)
{
    for (int m=0; m<10; m++)
    {
        if (some unhandled condition occurs)
        {
            break OuterLoop;
        }
        else
        {
            ...
        }
    }
}

However, C# does not support this construct and so goto must be used instead.

How to use it

To use it to escape from deeply nested loops, the above example needs to be modified thus:

    for (int n=0; n<10)
    {
        for (int m=0; m<10)
        {
            if (some unhandled condition occurs)
            {
                goto EndOfOuterLoop;
            }
            else
            {
                ...
            }
        }
    }
EndOfOuterLoop:
    // goto jumps to this point
    ...

No comments yet. Be the first.

Leave a reply

Close