diff --git a/rules/S2223/csharp/rule.adoc b/rules/S2223/csharp/rule.adoc index 5cbf2b0ddd..94ac164b5a 100644 --- a/rules/S2223/csharp/rule.adoc +++ b/rules/S2223/csharp/rule.adoc @@ -1,4 +1,11 @@ -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. +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 @@ -8,7 +15,7 @@ A ``++static++`` field that is neither constant nor read-only is not thread-safe public class Math { public static double Pi = 3.14; // Noncompliant -} +} ---- or @@ -20,8 +27,8 @@ public class Shape private class EmptyShape : Shape { - } -} + } +} ---- @@ -32,7 +39,7 @@ public class Shape public class Math { public const double Pi = 3.14; -} +} ---- or @@ -40,12 +47,12 @@ or ---- public class Shape { - public static readonly Shape Empty = new EmptyShape(); + public static readonly Shape Empty = new EmptyShape(); private class EmptyShape : Shape { - } -} + } +} ----