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

96,628

Solution 1

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.

Solution 2

I remember this part

switch (a)     
{ 
    case 3: 
        b = 7;
        // We want to drop through into case 4, but C# doesn't let us
    case 4: 
        c = 3;
        break; 
    default: 
        b = 2;
        c = 4;
        break; 
}

To something like this

switch (a)     
{
    case 3: 
        b = 7;
        goto case 4;    
    case 4: 
        c = 3;
        break;     
    default: 
        b = 2;
        c = 4;
        break;
}

Refer This

Solution 3

I use it extensively in Eduasync to show the kind of code that the compiler generates for you when using async methods in C# 5. You'd see the same thing in iterator blocks.

In "normal" code though, I can't remember the last time I used it...

Solution 4

The compiler uses goto statements in various pieces of generated code, for example in generated iterator block types (generated when using the yield return keyword - I'm pretty sure that the generated XML serialisation types also have a few goto statements in there somewhere too.

See Iterator block implementation details: auto-generated state machines for some more details on why / how the C# compiler handles this.

Other than generated code there isn't a good reason to use a goto statement in normal code - it makes the code harder to understand and as a result more error-prone. On the other hand using goto statements in generated code like this can simplify the generation process and is normally fine because nobody is going to read (or modify) the generated code and there is no chance of mistakes being made because a machine is doing the writing.

See Go-to statement considered harmful for an argument against goto as well as a classic piece of programming history.

Solution 5

I don't remember ever using goto. But maybe it improves the intent of a forever loop that you really never want to exit (no break, but you can still return or throw):

forever: {
  // ...
  goto forever;
}

Then again, a simple while (true) should suffice...

Also, you could use in a situation where you want the first iteration of a loop to start in the middle of the loop: look here for an example.

Share:
96,628

Related videos on Youtube

Brian Scott
Author by

Brian Scott

Updated on July 08, 2022

Comments

  • Brian Scott
    Brian Scott almost 2 years

    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

    • Grant Thomas
      Grant Thomas almost 13 years
      When you do need to use it, you've probably painted yourself into corner.
    • Admin
      Admin almost 13 years
      Possibly related question, stackoverflow.com/questions/2542289/…
    • Massif
      Massif almost 13 years
      what do you mean "still"? Was there a period of time people used it all the time [in c#]?
    • Brian Scott
      Brian Scott almost 13 years
      @Massif: "still" was intended to emphasise the modern opinion of the use of "goto" as a prelude to spaghetti code and a lack of readbility in source code. Very rarely do you see any code examples including this particular keyword which was why I was interested in asking in the first place.
    • Eric Lippert
      Eric Lippert almost 13 years
      If the reader "jumping around" the code is bad practice then do you also avoid "break", "continue", "throw", and "return"? They all cause a branch in control flow, sometimes a non-local branch. "Throw" doesn't even tell you where it is going, unlike goto.
    • Nitin Sawant
      Nitin Sawant over 10 years
      I use goto to break a loop and go back to starting statement according to specific condition
    • RoboJ1M
      RoboJ1M over 10 years
      We're allowed to use break to for-loop around a list looking for something and then break out when it's found (made redundant by linq now), throw in special circumstances (business logic exception, you should validate first and there is only ever one place where it could go and that's the entry point catch handler for the Dll you're in) and you're only allowed one return and it's the last line of the method. Never heard of continue @EricLippert
    • eaglei22
      eaglei22 about 6 years
      I like goto. I tried avoiding it because of the trend of people saying to avoid it because it makes code harder to read. Having learned Assembly language and branch statements, I think sometimes there are times, it may make the code more readable. I do think multiple uses in one method and jumping too far down in the code can do more harm than good. But if you are thinking a goto would work nicely here, a simple goto once in a while should not have you going out of your way to avoid just because the common consensus is to avoid it.
  • Jon Skeet
    Jon Skeet almost 13 years
    Normally I'd try to refactor this to put the loops in a separate method which I could just return from...
  • manojlds
    manojlds almost 13 years
    @Heinzi - I have not seen goto being warranted. Like Jon says, if it is being "warranted", the code is begging to be refactored.
  • mihsathe
    mihsathe almost 13 years
    I dunno about C#, but java gives you break <label> which ensures reliability as well as security.
  • Jesus Ramos
    Jesus Ramos almost 13 years
    labeled break, just a longer way of saying goto because it does the same freakin thing....
  • Brian Scott
    Brian Scott almost 13 years
    Surely "break" / "continue" are better approaches to loop management rather than requiring the code editor to jump around the source code trying to understand where the next step occurs?
  • mihsathe
    mihsathe almost 13 years
    @Jesus but then with goto, you can go anywhere. Labeled break ensures you are going just outside the loop.
  • Brian Scott
    Brian Scott almost 13 years
    can you provide a small example of why this approach was preferred or was it simply a personal preference?
  • Jesus Ramos
    Jesus Ramos almost 13 years
    Unless you're being adventurous and using goto with an address (i've seen it done before) then that problem is mitigated. And I doubt someone is using detour hooks in your C# and Java code to exploit goto statements.
  • Jesus Ramos
    Jesus Ramos almost 13 years
    Not if you have nested loops.
  • Brian Scott
    Brian Scott almost 13 years
    ok, I can see this as a valid scenario.
  • Jon Skeet
    Jon Skeet almost 13 years
    @Brian: It's not really clear what you mean. Eduasync shows the equivalent C# code to what the compiler does for you - and it generates code which uses goto, effectively...
  • Jodrell
    Jodrell almost 13 years
    In an error condition, you should consider throwing an exception.
  • Brian Scott
    Brian Scott almost 13 years
    I actually see this as the most valid reason to use [goto] yet. At least in this scenario it increases readability for programmers unaware that cases drop into each other without a break statement.
  • Jesus Ramos
    Jesus Ramos almost 13 years
    If you want to handle the error internally without an exception this would be a valid way to do so.
  • Jodrell
    Jodrell almost 13 years
    @Brian Scott, V4Vendetta. Unless I'm mistaken the first statement doesn't compile in C#. That would aid the programmer's understanding.
  • Stephen
    Stephen over 12 years
    You would want to break out of a loop if there is no point in keeping the execution of the loop. Otherwise you'll end up wasting more processing time in longer loops for no reason.
  • Brian Scott
    Brian Scott over 12 years
    @Kirk, this sounds like an opinion rather than anything quantitive?
  • o0'.
    o0'. over 10 years
    This is stupid: there are several cases were goto is useful, as illustrated by other answers. Either you rubut them explicitly, or just saying "it is wrong" is, well, wrong.
  • Justin
    Justin over 10 years
    @Lohoris I'm not buying it - every example I've seen where goto "improves readability" (including the answers here) would be far more readable after some simple refactoring.
  • o0'.
    o0'. over 10 years
    @Justin no, sometimes nested loops are just the most natural way of doing something, for instance if you are traversing an array of arrays.
  • Justin
    Justin over 10 years
    @Lohoris Often the natural way of coding something is just the way that the programmer is most familiar with - "natural" doesn't always correlate with "readable". What is wrong with a simple return for breaking out of nested loops? Although Purists would still disagree with this, that's not necessarily a view that I subscribe to.
  • o0'.
    o0'. over 10 years
    @Justin you need it to be a function to have return.
  • Justin
    Justin over 10 years
    @Lohoris Then refactor it into a function
  • o0'.
    o0'. over 10 years
    @Justin it's not always clearer to have it into a function. You're forcing something (having a function) just to avoid something you hate religiously (using a goto). Clear indication of doing something wrong.
  • Justin
    Justin over 10 years
  • Chris Marisic
    Chris Marisic over 9 years
    Taking a dynamic object and walking it's object graph that contains multiple dictionaries to get down to the values I need. Doesn't make sense to use methods that have a parameter of dynamic yet expect an exact object shape. With goto to break out multiple layers and continue walking through a collection of these objects. [I don't own the types so I can't provide better access, so reflection or dynamic it is]
  • Stephen Holt
    Stephen Holt over 8 years
    V4Vendetta why did you insert a break on the first code snippet...? It was better to show it without the break, otherwise the two snippets do different things. The reason why you need the goto in the second example is precisely because the first one doesn't compile in C# (as it would in C).
  • Dan Bechard
    Dan Bechard about 8 years
    @Justin Functions calls have overhead. goto does not. Something to consider.
  • user2864740
    user2864740 over 5 years
    The [C#] compiler 'using [goto] IL internally' is irrelevant to supporting goto in the C# language. It may be relevant to X-transpiled-to-C# code, but that's a different situation. The inverse is probably more useful: having goto in C# allows IL de-compilers 'an easy way' to get back to C#.
  • user2864740
    user2864740 over 5 years
    The linked answer contains an "interesting" use of goto.. and while(true) {..} is not an interesting use ..
  • Jack
    Jack over 2 years
    This is rather interesting but I don't know if I'd use that in production code