4.2 Goto Statement
C # allows you to tag lines of code so that you can jump directly to them using a goto statement. The advantages and disadvantages of this statement coexist. The main advantage is that this is an easy way to control when to execute which code. The main drawback is that using this technique too much will make the code obscure and confusing.
The Goto statement uses the following:
Goto <labelName>;
The label is defined in the following way:
<labelname>:
For example, the following code:
int myinteger = 5;
Goto MyLabel;
Myinteger + = 10;
MyLabel:
Console.WriteLine ("Myinteger = {0}", Myinteger);
The following procedures are performed:
? The Myinteger declaration is of type int and is given a value of 5.
? The goto statement interrupts the normal execution process and transfers control to the line of code labeled MyLabel:
? The value of the Myinteger is written to the console.
the following line 3rd code is never executed .
int myinteger = 5;
Goto MyLabel;
Myinteger + = 10;
MyLabel:
Console.WriteLine ("Myinteger = {0}", Myinteger);
In fact, if you add this code to your application, you will find that when you compile the code, the Error List window displays a warning, "code that has been detected unreachable" (Unreachable codes detected) and a line number. In the line of code that cannot be executed, there is a green wavy line underneath the Myinteger.
Goto statements have their effects, but they can also cause code to get into confusion. try not to use it (Use the techniques described later in this chapter to avoid using it.)
(original) C # learning Note 04--Process Control 02--goto statement