The goto Statement

C# enables you to label lines of code and then jump straight to them using the goto statement. This has its benefits and problems. The main benefit is that it ’ s a simple way to control what code is executed when. The main problem is that excessive use of this technique can result in difficult-to-understand spaghetti code.
The goto statement is used as follows:
goto < labelName > ;
Labels are defined as follows:
< labelName > :
For example, consider the following:

int myInteger = 5;
goto myLabel;
myInteger += 10; // never executed
Console.WriteLine("myInteger = {0}", myInteger);

Execution proceeds as follows:

  1. myInteger is declared as an int type and assigned the value 5 .
  2. The goto statement interrupts normal execution and transfers control to the line marked
    myLabel :.
  3. The value of myInteger is written to the console.

In fact, if you try this out in an application, this is noted in the Error List window as a warning when you try to compile the code, labeled “ Unreachable code detected , ” along with location details. You will also see a wavy green line under myInteger on the unreachable line of code. goto statements have their uses, but they can make things very confusing indeed. The following example shows some spaghetti code arising from the use of goto :

int myInteger = 5;
goto addVal;
Console.WriteLine("myInteger = {0}", myInteger);
goto start;
myInteger += 10;
goto writeResult;