private void btnGoto_Click(object sender, System.EventArgs e) { long lngCounter = 0; IncrementCounter: lngCounter++; if (lngCounter < 5000) goto IncrementCounter; }
Dimensions a long variable called lngCounter.
Sets the new variable to 0.
Defines a code label titled IncrementCounter. One or more goto statements can be used to jump code execution to this label at any time.
Increments lngCounter by 1.
Uses an if statement to determine if lngCounter has exceeded 5000. If it hasn't, a goto statement forces code execution back to the IncrementCounter label, where lngCounter is incremented and tested again, creating a loop.
This code works, and you're welcome to try it. However, this is terrible code. Remember how I said that the use of a goto can often be replaced by a better coding approach? In this case, C# has specific looping constructs that you'll learn about in the next hour. These looping constructs are far superior to building your own loop under most conditions, so you should avoid building a loop using a goto statement. In fact, one of the biggest misuses of goto is using it in place of one of C#'s internal looping constructs. In case you're interested, here's the loop that would replace the use of goto in this example:
for(long lngCounter = 0; lngCounter<=5000; lngCounter++) ...
This discussion may leave you wondering why you would ever use goto. One situation in which I commonly use goto statements is to create single exit points. As you know, you can force execution to leave a method at any time using return. Often, clean-up code is required before a method exits. In a long method, you may have many return statements. However, such a method can be a problem to debug because clean-up code may not be run under all circumstances. Because all methods have a single entry point, it makes sense to give them a single exit point. With a single exit point, you use a goto statement to go to the exit point, rather than use a return statement. The following procedure illustrates using goto to create a single exit point:
private void btnGoto_Click(object sender, System.EventArgs e) { ... ... // If it is necessary to exit the code, perform a goto to // the PROC_EXIT label, rather than using an Exit statement. PROC_EXIT: ... return; }
13.58.216.74