Static Class
ID |
csharp.static_class |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
CSharp |
Tags |
code-style, design |
Description
Reports plain classes whose members are all static and could therefore be declared
static class. A private parameter-less constructor (the pre-2.0 idiom for a hidden
constructor) is tolerated.
Rationale
A static class documents the design intent — "this type is a namespace for related
helpers, it is never instantiated" — and the compiler enforces it. Without the modifier
the class can be instantiated, inherited from and extended with instance state by a later
edit, and consumers cannot tell at a glance that those operations are unintended. Marking
the type static removes the ambiguity and turns accidental misuse into a compile error.
public class MathHelpers // FLAW
{
public static int Add(int a, int b) => a + b;
public static int Mul(int a, int b) => a * b;
}
public static class StringHelpers // OK, already static
{
public static string Trim(string s) => s?.Trim() ?? string.Empty;
}
public class Counter // OK, holds instance state
{
private int _count;
public void Inc() => _count++;
}
Remediation
Add the static modifier to the class declaration and remove any leftover
parameter-less private constructor; the compiler will then forbid future instance
members.