Curriculum
In C#, the goto
keyword is used to transfer control to a labeled statement in the code. The goto
statement can be used to create loops, jump over blocks of code, and handle error conditions. However, the use of goto
is generally discouraged because it can make code difficult to read and maintain.
Here’s an example of using the goto
keyword to create a loop:
int i = 0; loop: Console.WriteLine(i); i++; if (i < 10) { goto loop; }
In this example, the goto
statement is used to jump back to the loop
label, which creates a simple loop that prints the values of i
from 0
to 9
to the console.
The goto
keyword can also be used to handle error conditions, as shown in the following example:
int num = int.Parse(Console.ReadLine()); if (num < 0) { Console.WriteLine("Error: negative number"); goto end; } Console.WriteLine("The square of {0} is {1}", num, num*num); end: Console.WriteLine("End of program");
In this example, if the user enters a negative number, the program prints an error message and jumps to the end
label, skipping the calculation of the square of the number.
The rules for using the goto
keyword in C# are as follows:
goto
statement can only transfer control to a labeled statement within the same method.goto
statement.goto
statement cannot be used to transfer control to a block of code defined by a conditional statement (such as an if
or switch
statement).In summary, the goto
keyword can be a useful tool for creating loops and handling error conditions in C# programs. However, its use should be limited to cases where other control structures (such as loops and conditional statements) are not sufficient, and its use should be carefully considered to avoid creating hard-to-read and hard-to-maintain code.