There are several valid uses for goto in .NET (C #):
Simulated switch expression "Falling semantics . "
Those that come from the C ++ background are used to write switch statements that automatically switch from case to case, unless explicitly terminated with break. For C #, only trivial (empty) cases are possible.
For example, in C ++
int i = 1; switch (i) { case 1: printf ("Case 1\r\n"); case 2: printf ("Case 2\r\n"); default: printf ("Default Case\r\n"); break; }
In this C ++ code, the output is:
Case 1
Case 2
Default case
Here is a similar C # code:
int i = 1; switch (i) { case 1: Console.Writeline ("Case 1"); case 2: Console.Writeline ("Case 2"); default: Console.Writeline ("Default Case"); break; }
As written, this will not compile. There are several compilation errors that look like this:
Control cannot fall through from one case label ('case 1:') to another
Adding goto statements does the job:
int i = 1; switch (i) { case 1: Console.WriteLine ("Case 1"); goto case 2; case 2: Console.WriteLine("Case 2"); goto default; default: Console.WriteLine("Default Case"); break; }
... another useful use of goto in C # is ...
Endless loops and extended recursion
I will not go into details here, since it is less useful, but sometimes we write endless loops using while(true) constructors that explicitly terminate with break or re-execute with the continue statement. This can happen when we try to simulate calls to recursive methods, but have no control over the potential scope of the recursion.
You can obviously convert this to a while(true) or reorganize it into a separate method, but also use the label and goto statement.
This use of Goto is more controversial, but still something is worth keeping in mind as an option in very rare cases.