Click here to Skip to main content
15,878,871 members
Articles / Programming Languages / C#

Why goto Still Exists in C#

Rate me:
Please Sign up or sign in to vote.
2.91/5 (14 votes)
25 Jul 2009CPOL3 min read 76.9K   10   32
Developers, Software Engineers, and Programmers are logical, rational, reasonable people right? Sure they are…until you disagree with something they believe in. Then they can become the most enflamed, outraged, foaming-at-the-mouth, intolerant, lunatics you've ever had the pleasure of meeting.

Developers, Software Engineers, and Programmers are logical, rational, reasonable people right? Sure they are… until you disagree with something they believe in. Then they can become the most enflamed, outraged, foaming-at-the-mouth, intolerant, lunatics you've ever had the pleasure of meeting.

Take for instance the goto command. It can create emotions as intense as those raised during the ancient 'tabs versus spaces' debates or whether or not curly braces should be aligned in columns. (For the record, developers who use tabs and don't line up curly braces also kick puppies and do not practice good hygiene).

You can program for years and never use a goto. However, there are times when a goto can make the code simpler and that… is a very good thing.

Here's a scenario: You are working on a multi-threaded real-time program. You can't use the debugger because stepping through the code would mess up the timings and interactions between the threads. You also need something to help diagnose problems in the field. A runtime log that can be turned on and off is used. The requirement is that every function will log its entry and exit point. That way if something goes wrong, the log will show what function failed and where it failed.

In one area of the program, you need to perform several steps in sequence. If any step fails, the remaining steps must not execute.

Here's the first attempt:

C#
void DoProcess1()
{
    LOG("DoProcess Started...");
 
    if (Step1() == true)
        if (Step2() == true)
            if (Step3() == true)
                if (Step4() == true)
                    if (Step5() == true)
                        if (Step6() == true)
                            Step7();
 
    LOG("DoProcess Finished");
}

Sure it works but getting code to work is only the first step. Creating clear, maintainable code is the goal. If the code can be simplified, you are not done.

Second attempt, use a flag variable:

C#
// Do Process using a success flag
void DoProcess2()
{
    LOG("DoProcess Started...");
 
    bool Success;
 
    Success = Step1();
    if (Success == true)
        Success = Step2();
    if (Success == true)
        Success = Step3();
    if (Success == true)
        Success = Step4();
    if (Success == true)
        Success = Step5();
    if (Success == true)
        Success = Step6();
    if (Success == true)
        Success = Step7();
 
    LOG("DoProcess Finished");
}

That's better, but it can be simplified further:

Third attempt with goto:

C#
// DoProcess using goto
void DoProcess3()
{
    LOG("DoProcess Started...");
 
    if (Step1() == false)
        goto EXIT;
    if (Step2() == false)
        goto EXIT;
    if (Step3() == false)
        goto EXIT;
    if (Step4() == false)
        goto EXIT;
    if (Step5() == false)
        goto EXIT;
    if (Step6() == false)
        goto EXIT;
    if (Step7() == false)
        goto EXIT;
 
EXIT:
    LOG("DoProcess Finished");
}

The creation, assigning and checking of a variable has been eliminated. It also runs faster but the speed improvement is insignificant and not a reason for using a goto.

The example is trivial, however in real life, being able to jump to the end of complicated functions can dramatically reduce the complexity of code.

Before you disagree with the inclusion of the goto in the C# language, remember you are disagreeing with the people who created the language. You are also disagreeing with Steve McConnel the author of "Code Complete". Here's his chapter on gotos.

In my career, I've only used a goto once and I had to present the code to a code-review group of four developers. When I showed the code with and without the goto, they unanimously agreed without any discussion that goto was… the way to go. Pun intended.

I hope someone finds this helpful.

[Update: July 3, 2009]

Here are two more examples of when a goto is helpful. The first is from Charles Petzold’s book “.NET Book Zero” a free PDF book available is at http://www.charlespetzold.com/.

A switch “fall through” is illegal in C# (this causes a compiler error):

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

To get it to work, you can use a goto:

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

This example shows better how to cleanly get out of nested loops/code. The task is to search a three dimensional array and check for a null value:

C#
bool GetData()
{
    String[, ,] Data = new String[5, 5, 5];

    // ....code to fill in array here
    for (int x = 0; x < 5; x++)
    {
        for (int y = 0; y < 5; y++)
        {
            for (int z = 0; z < 5; z++)
            {
                if (Data[x, y, z] == null)
                    goto NULL_FOUND;
            }
        }
    }
    return true;

NULL_FOUND:
    Response.Write("Invalid Data");
    return false;
}

Steve Wellens

This article was originally posted at http://weblogs.asp.net/stevewellens/privaterss.aspx

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
EndWell Software, Inc.
United States United States
I am an independent contractor/consultant working in the Twin Cities area in Minnesota. I work in .Net, Asp.Net, C#, C++, XML, SQL, Windows Forms, HTML, CSS, etc., etc., etc.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Danny Chu28-Feb-14 2:06
Danny Chu28-Feb-14 2:06 
GeneralRe: My vote of 1 Pin
Steve Wellens28-Feb-14 16:00
Steve Wellens28-Feb-14 16:00 
GeneralComplex nested loops... Pin
barbrady12341-Nov-13 9:13
barbrady12341-Nov-13 9:13 
GeneralRe: Complex nested loops... Pin
Steve Wellens1-Nov-13 14:44
Steve Wellens1-Nov-13 14:44 
GeneralMy vote of 2 Pin
Jouke van der Maas5-Jun-09 1:30
Jouke van der Maas5-Jun-09 1:30 
General[My vote of 1] Oh well.. Pin
Jouke van der Maas5-Jun-09 1:29
Jouke van der Maas5-Jun-09 1:29 
GeneralRe: [My vote of 1] Oh well.. Pin
Steve Wellens5-Jun-09 1:39
Steve Wellens5-Jun-09 1:39 
GeneralMy vote of 1 Pin
Jon Artus3-Jun-09 3:01
Jon Artus3-Jun-09 3:01 
GeneralWhy Pin
Member 38638312-Jun-09 5:01
Member 38638312-Jun-09 5:01 
GeneralMy vote of 2 Pin
Harshdeep Mehta (4700787)2-Jun-09 4:15
Harshdeep Mehta (4700787)2-Jun-09 4:15 
GeneralMy vote of 1 Pin
p_a_k1-Jun-09 23:43
p_a_k1-Jun-09 23:43 
GeneralRe: My vote of 1 Pin
deroage2-Jun-09 3:14
deroage2-Jun-09 3:14 
GeneralMy vote of 1 Pin
NikoTanghe1-Jun-09 22:54
NikoTanghe1-Jun-09 22:54 
GeneralMy vote of 1 Pin
arepetti1-Jun-09 22:27
arepetti1-Jun-09 22:27 
GeneralRe: My vote of 1 Pin
Steve Wellens2-Jun-09 3:07
Steve Wellens2-Jun-09 3:07 
GeneralAnother way to re-factor this. Pin
Stephen Brannan1-Jun-09 19:48
Stephen Brannan1-Jun-09 19:48 
Generaltry ... finally PinPopular
gmt521-Jun-09 19:44
gmt521-Jun-09 19:44 
// DoProcess using goto
void DoProcess4()
{
    LOG("DoProcess Started...");
 
    try
    {
      if (!Step1()) return;
      if (!Step2()) return;
      // ... the rest ...
    }
    finally
    {
       LOG("DoProcess Finished");
    }
}


another way to do this ...
GeneralRe: try ... finally Pin
Steve Wellens2-Jun-09 4:54
Steve Wellens2-Jun-09 4:54 
GeneralRe: try ... finally Pin
merlin9812-Jun-09 4:56
professionalmerlin9812-Jun-09 4:56 
Generaltry this Pin
T.D.Brown1-Jun-09 17:41
T.D.Brown1-Jun-09 17:41 
GeneralRe: try this Pin
Stephen Brannan1-Jun-09 19:50
Stephen Brannan1-Jun-09 19:50 
GeneralRe: try this Pin
Steve Wellens2-Jun-09 2:58
Steve Wellens2-Jun-09 2:58 
GeneralI don't believe GOTOs are needed Pin
The_Mega_ZZTer1-Jun-09 17:26
The_Mega_ZZTer1-Jun-09 17:26 
GeneralI don't think that's the reason for goto to still exists Pin
tvbusy1-Jun-09 16:08
tvbusy1-Jun-09 16:08 
GeneralRe: I don't think that's the reason for goto to still exists Pin
Steve Wellens1-Jun-09 16:16
Steve Wellens1-Jun-09 16:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.