C# > Core C# > Control Flow > goto Statement
Goto for Switching Logic (Anti-Pattern)
This snippet showcases an anti-pattern using goto
to mimic switch-case behavior. While technically functional, this approach is strongly discouraged due to poor readability and maintainability.
Code Demonstration
This code attempts to simulate a switch
statement using if-else
conditions and goto
statements. Based on the value of the choice
variable, the code jumps to the corresponding case
label. Each case
then uses another goto
statement to jump to the end
label to avoid falling through to the next case. This is a complex and hard-to-read approach and should be avoided in favor of a standard switch statement.
using System;
public class GotoSwitchExample
{
public static void Main(string[] args)
{
int choice = 2;
if (choice == 1)
{
goto case1;
}
else if (choice == 2)
{
goto case2;
}
else
{
goto defaultCase;
}
case1:
Console.WriteLine("You chose option 1.");
goto end;
case2:
Console.WriteLine("You chose option 2.");
goto end;
defaultCase:
Console.WriteLine("Invalid choice.");
goto end;
end:
Console.WriteLine("Program finished.");
}
}
Why This Is an Anti-Pattern
goto
statements. It's difficult to quickly understand the program's logic.goto end;
statement can lead to unintended fall-through behavior.if-else
chain and the separate goto
statements for each case are redundant and add unnecessary complexity.
The Preferred Approach: Switch Statement
The switch
statement provides a clear and concise way to handle multiple cases based on the value of a variable. It automatically prevents fall-through behavior (unless explicitly intended) and is much easier to read and maintain than the goto
-based approach. The break
statement is used to exit the switch block after executing the code for the matching case.
using System;
public class SwitchExample
{
public static void Main(string[] args)
{
int choice = 2;
switch (choice)
{
case 1:
Console.WriteLine("You chose option 1.");
break;
case 2:
Console.WriteLine("You chose option 2.");
break;
default:
Console.WriteLine("Invalid choice.");
break;
}
Console.WriteLine("Program finished.");
}
}
Best Practices
Always favor the switch
statement over goto
when implementing branching logic based on multiple conditions. The switch
statement provides better structure, readability, and maintainability.
FAQ
-
What is an anti-pattern?
An anti-pattern is a commonly used but ineffective or counterproductive solution to a problem. It's a practice that appears to be a good idea initially but ultimately leads to negative consequences, such as reduced code quality, increased complexity, or difficulty in maintenance. -
Why is fall-through behavior in a switch statement sometimes useful?
Fall-through behavior (where execution continues to the next case without abreak
statement) can be useful in specific scenarios where multiple cases should execute the same code. However, it should be used intentionally and documented clearly to avoid confusion.