C# Goto Statement

In C#, the goto statement allows you to transfer control to a labeled statement within the same method, block, or switch statement. It provides an unconditional jump to the specified label, bypassing any code in between.

The basic syntax of the goto statement is as follows:

goto label;

Here, label is the identifier of a labeled statement within the same method, block, or switch statement. For example:

start:
Console.WriteLine("This is the start of the program.");

// Some code...

goto end;

// This code will be skipped.
Console.WriteLine("This code won't be executed.");

end:
Console.WriteLine("This is the end of the program.");

In the above example, the program will start execution from the start label. It will then print “This is the start of the program.” Next, it will encounter the goto statement, which transfers control to the end label. As a result, the code between the goto statement and the end label is skipped, and “This code won’t be executed.” is not printed. Finally, the program reaches the end label and prints “This is the end of the program.”

It’s important to use the goto statement judiciously because it can make the code harder to read and understand. Unrestricted use of goto statements can lead to spaghetti code and make debugging and maintenance more challenging. In general, it’s advisable to utilize structured programming constructs like loops, conditional statements, and methods to control program flow rather than relying on goto statements.