Duplicate Branches

ID

csharp.duplicate_branches

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

CSharp

Tags

duplicate-code, reliability

Description

Reports an if / else if chain in which two branches have structurally identical bodies. Two branches running the same code under different conditions is almost always a copy-paste mistake: either one of the bodies was intended to differ and the change was forgotten, or the branches should be merged into a single condition.

A branch whose body is a single line of code — one statement, or none at all (an empty or comment-only body) — is never compared: repeating one short statement across the arms of a dispatch chain (if (kind == 1) return HandleA(); else if (kind == 2) return HandleA();) is a common, deliberate idiom rather than a copy-paste accident, and a comment-only body carries no code to duplicate in the first place. Only a genuine multi-statement duplicate is reported.

Rationale

A chain such as if (A) { X; } else if (B) { X; } collapses to if (A || B) { X; }. As written, the duplicated body suggests that the second body was meant to behave differently and a maintainer reading the chain will spend time looking for the difference that is not there. Either fix the diverging branch or fold the conditions together.

if (kind == Kind.A)                 // OK
{
    int x = 1;
    HandleValue(x);
}
else if (kind == Kind.B)            // FLAW — multi-statement body identical to the previous branch
{
    int x = 1;
    HandleValue(x);
}
else                                // OK — distinct body
{
    HandleOther();
}

if (kind == Kind.A)                 // OK — single-statement dispatch-chain idiom
    return HandleA();
else if (kind == Kind.B)            // OK — repeating one short statement is deliberate
    return HandleA();

Remediation

Inspect every branch in the chain. If two branches really should do the same thing, merge them with ||. If they should differ, restore the missing behaviour in the duplicated branch.