Why is this an issue?
Non-private static
fields that are neither const
nor readonly
can lead to errors and unpredictable
behavior.
This can happen because: * Any object can modify these fields and alter the global state. This makes the code more difficult to read, debug and
test. * Correctly accessing these fields from different threads needs synchronization with lock
. Improper synchronization may lead to
unexpected results.
Publicly visible static fields should only be used to store shared data that does not change. To enforce this intent, these fields should be marked
readonly
or converted to const
.
Noncompliant code example
public class Math
{
public static double Pi = 3.14; // Noncompliant
}
or
public class Shape
{
public static Shape Empty = new EmptyShape(); // Noncompliant
private class EmptyShape : Shape
{
}
}
Compliant solution
public class Math
{
public const double Pi = 3.14;
}
or
public class Shape
{
public static readonly Shape Empty = new EmptyShape();
private class EmptyShape : Shape
{
}
}