rspec/rules/S2696/csharp/rule.adoc
Jamie Anderson 9ee16daa47
Modify rules: Add STIG AS&D 2023-06-08 mappings (#3914)
* Update JSON schema to include STIG ASD 2023-06-08 mapping

* Update rules to add STIG metadata mappings

---------

Co-authored-by: Loris Sierra <loris.sierra@sonarsource.com>
2024-05-06 08:56:31 +02:00

76 lines
2.3 KiB
Plaintext

This rule raises an issue each time a `static` field is updated from a non-static method or property.
== Why is this an issue?
Updating a `static` field from a non-`static` method introduces significant challenges and potential bugs. Multiple class instances and threads can access and modify the `static` field concurrently, leading to unintended consequences for other instances or threads (unexpected behavior, https://www.c-sharpcorner.com/UploadFile/1d42da/race-conditions-in-threading-C-Sharp/[race conditions] and synchronization problems).
[source,csharp]
----
class MyClass
{
private static int count = 0;
public void DoSomething()
{
//...
count++; // Noncompliant: make the enclosing instance property 'static' or remove this set on the 'static' field.
}
}
interface MyInterface
{
private static int count = 0;
public void DoSomething()
{
//...
count++; // Noncompliant: remove this set, which updates a 'static' field from an instance method.
}
}
----
== Resources
=== Documentation
* https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members[Static Classes and Static Class Members]
* https://learn.microsoft.com/en-us/dotnet/standard/threading/using-threads-and-threading[Using threads and threading]
=== Articles & blog posts
* https://www.c-sharpcorner.com/UploadFile/1d42da/race-conditions-in-threading-C-Sharp/[Race Conditions in C#]
include::../common/resources/standards.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Make the enclosing instance [method|property] "static" or remove this set on the "static" field.
* Remove this set, which updates a "static" field from an instance [method|property].
=== Highlighting
Primary: static field assignment
Secondary: static field declaration
'''
== Comments And Links
(visible only on this page)
=== on 24 Jun 2015, 07:03:57 Tamas Vajk wrote:
\[~ann.campbell.2] I've created this subtask, because in C# this rule can also apply for properties. Furthermore, the `synchronized static` part doesn't work for C#.
=== on 24 Jun 2015, 14:01:07 Ann Campbell wrote:
looks good [~tamas.vajk]
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]