Unused Private Field
ID |
csharp.unused_private_field |
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 private fields that are never referenced anywhere in their declaring type. Because
a private field is only reachable from within its own type, a field with no references is
dead code.
Rationale
An unreferenced private field wastes memory, lengthens the type, and invites confusion about
whether it carries state that matters. Fields decorated with an attribute are excluded: a
serializer, DI container, or engine ({@code [JsonProperty]}, {@code [DataMember]},
{@code [SerializeField]}) may read or write them by reflection, so "no source reference" does
not mean unused. Compile-time const declarations are a separate construct and are not
reported.
public class Cache
{
private int hits; // OK — used in Record
private int misses; // FLAW — never referenced
private readonly string name; // FLAW — never referenced
[System.Text.Json.Serialization.JsonInclude]
private int total; // OK — touched by serialization
public void Record()
{
hits++;
}
}