Unreachable Code
ID |
csharp.unreachable_code |
Severity |
low |
Remediation Complexity |
auto_fix |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Dead Code |
Language |
CSharp |
Tags |
dead-code, reliability |
Description
Reports a statement that can never execute because control flow always leaves the enclosing
region before reaching it. The analysis walks the method’s control-flow graph: code becomes
unreachable after an unconditional jump (return, throw, break, continue, goto), after
a never-returning call (Environment.Exit(…), Environment.FailFast(…)), or inside an
always-taken constant branch. Only the first statement of each dead region is flagged, and it
is almost always a leftover from an earlier edit.
Rationale
C# itself produces a CS0162 warning for some of these cases, but only when the compiler can prove the preceding statement always exits. Structurally detecting "any statement after an unconditional exit in the same block" catches the broader category and surfaces the dead code as part of the regular quality pass instead of relying on warnings being turned on and not silenced.
public int Compute(int n)
{
if (n < 0) throw new ArgumentException();
return n * 2;
int unused = 0; // FLAW — statement after return
}
public void Loop()
{
while (true)
{
break;
DoWork(); // FLAW — statement after break
}
}
public int Choose(bool flag)
{
if (flag) return 1; // OK — return is conditional, the rest still runs
return 2;
}
Remediation
Delete the unreachable statements, or, if the control-flow exit was added by mistake, remove or guard the exit so the following statements run.