rspec/rules/S2223/csharp/rule.adoc

75 lines
1.4 KiB
Plaintext

== 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
[source,csharp]
----
public class Math
{
public static double Pi = 3.14; // Noncompliant
}
----
or
[source,csharp]
----
public class Shape
{
public static Shape Empty = new EmptyShape(); // Noncompliant
private class EmptyShape : Shape
{
}
}
----
=== Compliant solution
[source,csharp]
----
public class Math
{
public const double Pi = 3.14;
}
----
or
[source,csharp]
----
public class Shape
{
public static readonly Shape Empty = new EmptyShape();
private class EmptyShape : Shape
{
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]