In C# goto statement is used to transfer the control directly to the labeled statement. This statement is used to get out of deeply nested loops. we can use the goto statement with different loops. Let's discuss the syntax of the goto statement.
goto statement;
In the above syntax first of all we will define the goto statement with the keyword goto. the statement is a labeled statement where we want to transfer the control of the program.
First of all, we will define a program with the usage of the goto statement after that we will discuss it step by step.
for (int i = 1; i < 100; i++)
{
if (i == 2)
{
goto Close;
}
Console.WriteLine(i);
}
Close: Console.WriteLine("For loop terminated");
In the above example when the value of the variable i ==2
then the goto statement transfers the control to the labeled statement which is Close and for loop should be terminated.
1
For loop terminated
With the switch statements, we can use multiple goto statements. for a better understanding let's see an example.
int i = 2;
switch (i)
{
case 1:
Console.WriteLine(i);
break;
case 2:
Console.WriteLine(i);
goto case 1;
case 3:
Console.WriteLine(i);
goto case 1;
default:
Console.WriteLine("Unknow selection");
break;
}
2
1
First of all, we assign the value to the variable i =2
switch statement transfer control to case 2 after the output of case 2 goto statement transfer control to the labeled statement which is case 1.