/
S2223_c#.html
44 lines (41 loc) · 1.18 KB
/
S2223_c#.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<p>Non-private <code>static</code> fields that are neither <code>const</code> nor <code>readonly</code> can lead to errors and unpredictable
behavior.</p>
<p>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 <code>lock</code>. Improper synchronization may lead to
unexpected results.</p>
<p>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
<code>readonly</code> or converted to <code>const</code>.</p>
<h2>Noncompliant Code Example</h2>
<pre>
public class Math
{
public static double Pi = 3.14; // Noncompliant
}
</pre>
<p>or</p>
<pre>
public class Shape
{
public static Shape Empty = new EmptyShape(); // Noncompliant
private class EmptyShape : Shape
{
}
}
</pre>
<h2>Compliant Solution</h2>
<pre>
public class Math
{
public const double Pi = 3.14;
}
</pre>
<p>or</p>
<pre>
public class Shape
{
public static readonly Shape Empty = new EmptyShape();
private class EmptyShape : Shape
{
}
}
</pre>