#986 – Using goto to Jump to a Label

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);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #986 – Using goto to Jump to a Label

  1. Pingback: Dew Drop – December 2, 2013 (#1674) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: