Method Could Be Static
ID |
csharp.method_could_be_static |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
CSharp |
Tags |
best-practice, efficiency |
Description
Reports a private instance method that never touches instance state — no this, no
base, and no unqualified reference to an instance field, property or method of the
enclosing class. Such a method does not need an instance and can be declared static.
Rationale
A method that ignores instance state is conceptually a free function. Marking it static
documents that it has no per-instance dependency, lets the compiler and JIT skip the
implicit this argument, and makes the method callable and testable without constructing
the type. The rule is deliberately limited to private methods so that making it static
never changes a type’s public contract, an override, or an interface implementation.
The rule also skips every method of a class that declares a base type, or that is
partial. In both cases, an unqualified name in the visible source may resolve to a
member this single-compilation-unit analysis cannot see — an inherited member, or a
member declared in another part of the partial class (typically generated designer/XAML
code-behind that is not in source control). A named-control field like MyMap in a XAML
view’s code-behind is a common example: it looks unresolved here, but flagging the method
static would not compile.
public class Calculator
{
private int factor = 2;
// FLAW — uses only its parameters, no instance state
private int Add(int a, int b) => a + b;
private int Square(int x) => x * x; // FLAW — could be static
// OK — reads the instance field 'factor'
private int Scale(int x) => x * factor;
// OK — already static
private static int Triple(int x) => x * 3;
}
Remediation
Add the static modifier to the method. If the method later needs instance state, the
modifier can simply be removed again.