rspec/rules/S2696/csharp/rule.adoc

76 lines
2.3 KiB
Plaintext
Raw Normal View History

This rule raises an issue each time a `static` field is updated from a non-static method or property.
2021-02-02 15:02:10 +01:00
== Why is this an issue?
2020-06-30 12:48:07 +02:00
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).
2020-06-30 12:48:07 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:48:07 +02:00
----
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
2020-06-30 12:48:07 +02:00
{
private static int count = 0;
public void DoSomething()
{
//...
count++; // Noncompliant: remove this set, which updates a 'static' field from an instance method.
2020-06-30 12:48:07 +02:00
}
}
----
== 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[]