35 lines
1.0 KiB
Plaintext
35 lines
1.0 KiB
Plaintext
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
|
|
|
|
----
|
|
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
|
|
}
|
|
}
|
|
----
|
|
|