rspec/rules/S3465/csharp/rule.adoc

52 lines
1.3 KiB
Plaintext
Raw Normal View History

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.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
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)
include::message.adoc[]
include::highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]