Switch Default First Or Last
ID |
csharp.switch_default_first_or_last |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
CSharp |
Tags |
code-style, control-flow, switch |
Description
Reports a switch statement whose default section sits between the case sections instead of
first or last. A section with stacked labels such as case 3: default: is judged by the position
of the whole section.
Rationale
The position of default makes no difference to the compiler, so it exists purely for the reader,
who scans the section list from one end looking for the fallback. A default in the middle is
routinely skipped during review, and it is usually the fossil of a case that somebody appended
after it rather than a deliberate layout choice.
public string Buried(int code)
{
switch (code)
{
case 1:
return "created";
default: // FLAW — neither first nor last
return "unknown";
case 2:
return "deleted";
}
}
public string AtTheEnd(int code)
{
switch (code)
{
case 1:
return "created";
case 2:
return "deleted";
default: // OK — last section
return "unknown";
}
}
Remediation
Move the default section to the end of the switch, or to the very beginning if the codebase
prefers to state the fallback up front. Keep the choice consistent across the project. Since C#
forbids implicit fall-through, moving a section never changes behaviour, provided any
goto case / goto default jumps keep referring to the same labels.