Search code examples
c#.netcoding-stylegoto

Does anyone still use [goto] in C# and if so why?


I was wondering whether anyone still uses the "goto" keyword syntax in C# and what possible reasons there are for doing so.

I tend to view any statements that cause the reader to jump around the code as bad practice but wondered whether there were any credible scenarios for using such a syntax?

Goto Keyword Definition


Solution

  • There are some (rare) cases where goto can actually improve readability. In fact, the documentation you linked to lists two examples:

    A common use of goto is to transfer control to a specific switch-case label or the default label in a switch statement.

    The goto statement is also useful to get out of deeply nested loops.

    Here's an example for the latter one:

    for (...) {
        for (...) {
            ...
            if (something)
                goto end_of_loop;
        }
    }
    
    end_of_loop:
    

    Of course, there are other ways around this problem as well, such as refactoring the code into a function, using a dummy block around it, etc. (see this question for details). As a side note, the Java language designers decided to ban goto completely and introduce a labeled break statement instead.