Why is this an issue?
A static field belongs to the type, not to one object. A visible static field can therefore be read or reassigned by any
code that can access the type.
When such a field is mutable, the type does not control when or why its shared state changes. This creates hidden dependencies between callers, makes code harder to test, and makes it difficult to later add validation or other rules for updates.
public class Limits
{
public static int DaysInWeek = 7; // Noncompliant: this fixed value should be a const
}
public class ApplicationInfo
{
public static Guid InstanceId = Guid.NewGuid(); // Noncompliant: this value is created once but can later be reassigned
}
public class Counters
{
public static int ErrorCount = 0; // Noncompliant: any caller can change this shared state
}
// Any caller can set or increment ErrorCount directly.
Counters.ErrorCount = -1;
Counters.ErrorCount++;
Choose the solution that matches the intended lifetime of the value:
- If the value is a fixed compile-time constant, use
const. - If the value must be created or calculated when the application starts and must not be reassigned, use
static readonly. - If the value must change, keep the field
privateand expose a small API that expresses the allowed updates. Prefer an instance owned by the application over global state when possible.
public class Limits
{
public const int DaysInWeek = 7; // A fixed fact known when the code is compiled
}
public class ApplicationInfo
{
public static readonly Guid InstanceId = Guid.NewGuid(); // A new value created once when the application starts
}
public sealed class ErrorCounter
{
private int errorCount; // A value that may change, but only through this class
public int ErrorCount => errorCount;
public void Increment() => errorCount++;
public void Reset() => errorCount = 0;
}