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. A read as the governing subject of a switch expression
(code switch { … }) or through a null-conditional invocation chain (handler?.Invoke(…))
also counts as a usage, even though these are less common reference shapes.
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
}
public string Describe(int code)
{
var status = code; // OK — read as the switch expression's subject
return status switch
{
200 => "OK",
_ => "Unknown"
};
}
public void RaiseUpdated()
{
var handler = Updated; // OK — read through the null-conditional invocation
handler?.Invoke(this, EventArgs.Empty);
}
public event EventHandler Updated;
private int ComputeSideEffect() => 0;
private System.IDisposable Open() => null;
}