Sams Teach Yourself C# in 24 Hours

Sams Teach Yourself C# in 24 Hours

By James Foxall and Wendy Haro-Chun

Branching Within Code Using goto

private void btnGoto_Click(object sender, System.EventArgs e)
{
   long lngCounter = 0;

IncrementCounter:
   lngCounter++;
   if (lngCounter < 5000) goto IncrementCounter;
}

This code does the following:

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;
}

Share ThisShare This

Informit Network