In c#, the Goto statement is used to transfer program control to the defined labeled statement, and it is useful to get out of the loop or exit from deeply nested loops based on our requirements.
Generally, in c#, the defined labeled statement must always exist in the goto statement's scope. We can define multiple goto statements in our application to transfer the program control to the specified labeled statement.
For example, we can use a goto statement in the switch statement to transfer control from one switch-case label to another or a default label based on our requirements.
Following is the syntax of defining a goto statement in the c# programming language.
If you observe the above syntax, we defined a goto statement using the goto keyword and labeled_statement. Here the labeled_statement is used to transfer the program control to a specified labeled_statement position.
Now we will see how to use the goto statement in c# for loop to get out of the loop at the particular condition with examples.
Following is the example of using the goto statement in for loop to exit the loop based on our requirements.
If you observe the above example, we used a goto in for loop with the labeled statement “endloop” to exit for loop whenever the variable (i) value equals 5.
When we execute the above c# program, we will get the result below.
If you observe the above result, whenever the variable (i) value equals 5, then the goto statement transferred the program control from for loop to the specified label statement (endloop) position.
In c#, we can use the goto statement exit from defined loops or transfer control to a specific switch-case label or the switch statement's default label based on our requirements.
Now we will see how to use the goto statement in the switch-case statement with an example. Following is the example of using goto with a switch-case statement to transfer control from one switch-case label to another based on our requirements.
If you observe the above example, we used a goto statement in multiple switch cases and trying to transfer program control from case 2 / case 3 to case 1.
When we execute the above c# program, we will get the result as shown below.
This is how we can use a goto statement with switch-case statements to transfer the program control from one case to another in c# programming language based on our requirements.
It’s better to avoid using the goto statement in our c# applications because it will make the program logic complex. It’s difficult to understand the process flow of program execution.