Unused Local Variable

ID

csharp.unused_local_variable

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Code Smell

Language

CSharp

Tags

CWE:563, code-style, unused-code

Description

Reports local variables that are declared in a method or block body but are never read afterwards. The variable is dead weight: it allocates a name and an initializer that nothing consumes.

Rationale

A local that is assigned but never used is at best clutter and at worst a sign of a real mistake — a value computed and then dropped, or a name that a later edit stopped referencing. Removing it makes the method shorter and removes a distraction for the reader. Discards (_), ref/out locals, and using resources are excluded because "never read locally" is the expected, correct shape for those.

public class Calculator
{
    public int Sum(int a, int b)
    {
        int unused = 99;            // FLAW — declared, never read
        int total = a + b;          // OK — read in the return
        return total;
    }

    public void Discard()
    {
        _ = ComputeSideEffect();    // OK — discard is an explicit "ignore this"
        using var stream = Open();  // OK — held for its Dispose() side effect
    }

    private int ComputeSideEffect() => 0;
    private System.IDisposable Open() => null;
}

Remediation

Delete the unused local. If it was meant to feed a later computation, restore that use; if the initializer has a needed side effect, keep the call but drop the assignment.