47 lines
940 B
Plaintext
47 lines
940 B
Plaintext
A ``++static++`` field that is neither constant nor read-only is not thread-safe. Correctly accessing these fields from different threads needs synchronization with ``++lock++``s. Improper synchronization may lead to unexpected results, thus publicly visible static fields are best suited for storing non-changing data shared by many consumers. To enforce this intent, these fields should be marked ``++readonly++`` or converted to constants.
|
|
|
|
|
|
== 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
|
|
{
|
|
}
|
|
}
|
|
----
|
|
|