#986 – Using goto to Jump to a Label
December 2, 2013 1 Comment
You can use the goto statement within a block of code to explicitly jump to another location in the code using a label.
Dog d = new Dog("Bob", 5); DoTraining: // Train my dog d.Train(); if (d.NumMinutesCanSit < 5) goto DoTraining; Console.WriteLine("My dog is trained!");
While you can use a goto statement to jump to a label, it’s almost always a bad idea to use goto in this way. You can always use structured programming techniques, like the while statement, rather than goto. Code containing goto statements is typically harder to understand than functionally equivalent code written using structured programming constructs.
Here’s the above block of code, re-written to use a while loop.
do d.Train(); while (d.NumMinutesCanSit < 5);