The goto Statement


C# allows 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 is a very simple way of controlling 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>; 

and labels are defined in the following way:

 <labelName>: 

For example, consider the following:

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

Execution proceeds as follows:

  • myInteger is declared as an int type and assigned the value 5.

  • The goto statement interrupts normal execution and transfers control to the line marked myLabel:.

  • The value of myInteger is written to the console.

The line of code highlighted below is never executed:

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

In fact, if you try this out in an application, you will see that 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.

goto statements have their uses, but they can make things very confusing indeed.

As an example of some spaghetti code arising from the use of goto, consider the following:

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

This is perfectly valid code, but very difficult to read! You might like to try this out for yourself and see what happens. Before doing that, though, try and work out what this code will do by looking at it, so you can give yourself a pat on the back if you're right.

You come back to this statement a little later, because it has implications for use with some of the other structures in this chapter (although, to be honest, I don't advocate its use).




Beginning Visual C# 2005
Beginning Visual C#supAND#174;/sup 2005
ISBN: B000N7ETVG
EAN: N/A
Year: 2005
Pages: 278

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net