Avoid Goto
ID |
csharp.avoid_goto |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
CSharp |
Tags |
code-style, control-flow |
Description
Reports any use of the goto statement, in any of its three C# forms:
goto label, goto case expr and goto default.
Rationale
goto introduces unstructured control flow that is hard to follow, breaks most static
analyses and rarely produces the clearest expression of a loop exit, error path or state
transition. The switch-section variants (goto case / goto default) are conventional in
hand-written state machines but they couple sibling sections together in a way that makes
the switch hard to refactor or extend.
public int Demo(int n)
{
if (n < 0) goto error; // FLAW
return n * 2;
error:
return -1;
}
public string Stage(int s)
{
switch (s)
{
case 0:
Console.WriteLine("warm up");
goto case 1; // FLAW
case 1:
return "ready";
default:
return "unknown";
}
}
Remediation
Replace goto with a structured construct: extract a helper method, use an early
return, a break / continue from a loop, or rewrite the switch sections so each one is
self-contained. If a switch genuinely shares logic between cases, extract the shared work
into a method that every case calls.