Using Jump Statements in C#
The goto, break, and continue statements are known as jump statements. You use them to transfer control from one point in the program to another, at any time. In this section, you will learn how to use jump statements in C# programs.
The goto Statement
The goto statement is the most primitive C# jump statement. It transfers control to a labeled statement. The label must exist and must be in the scope of the goto statement. More than one goto statement can transfer control to the same label.
if (number % 2 == 0)
goto Even;
Console.WriteLine("odd");
goto End;
Even:
Console.WriteLine("even");
End:;
The goto statement can transfer control out of a block, but it can never transfer control into a block. The purpose of this restriction is to avoid the possibility of jumping past an initialization. The same rule exists in C++ and other languages as well.
The goto statement and the targeted label statement can be very far apart in the code. This distance can easily obscure the control-flow logic and is the reason that most programming guidelines recommend that you do not use goto statements.
Note: The only situations in which goto statements are recommended are in switch statements or to transfer control to the outside of a nested loop.
The break and continue Statements
A break statement exits the nearest enclosing switch, while, do, for, or foreach statement. A continue statement starts a new iteration of the nearest enclosing while, do, for, or foreach statement.
The following code writes out the values zero through nine.
int i = 0;
while (true)
{
Console.WriteLine(i);
i++;
if (i <
10)
continue;
else
break;
}
The break and continue statements are not very different from a goto statement, whose use can easily obscure control-flow logic. For example, you can rewrite the while statement in the preceding example without using break or continue as follows:
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i++;
}
Preferably, you can rewrite the previous code by using a for statement, as follows:
for (int i = 0; i < 10; i++) {Console.WriteLine(i);
}