rspec/rules/S3465/csharp/rule.adoc

66 lines
1.6 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
A field marked ``++readonly++`` can only be assigned as part of its declaration or in a constructor. While ``++readonly++`` reference types (e.g. classes) can still have their state changed subsequently, the same is not true of value types such as ``++struct++`` s. Thus, calling a method that updates object state on a ``++readonly++`` value type field simply has no effect (but runs without error!). The result is code that probably doesn't do what you thought it did.
This rule raises an issue when a method that is not marked ``++[Pure]++`` is invoked on a ``++readonly++`` value type field.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
public struct S1
{
public int value;
public void SetValue()
{
value = 10;
}
}
class Test
{
static readonly S1 first;
static S1 second;
static void Main()
{
first.SetValue(); // Noncompliant
second.SetValue();
Console.WriteLine(first.value); // Surprise! This writes 0
Console.WriteLine(second.value); // This writes 10
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove the "readonly" modifier from "xxx", or add the "[Pure]" attribute to "yyy".
=== Highlighting
``++xxx.impureMethod++``
'''
== Comments And Links
(visible only on this page)
=== on 11 Dec 2015, 09:17:14 Tamas Vajk wrote:
\[~ann.campbell.2] I changed the title a bit.
=== on 11 Dec 2015, 15:54:48 Ann Campbell wrote:
\[~tamas.vajk] I made one further, minor change
endif::env-github,rspecator-view[]