Readonly structural behavior change

I am trying to understand some basic concepts:

class Program { private static readonly MyStruct m = new MyStruct(); static void Main(string[] args) { //new MutableSample().RunSample(); Console.WriteLine(m.ChangeInternal()); Console.WriteLine(m.ChangeInternal()); Console.WriteLine(m.ChangeInternal()); Console.Read(); } } public struct MyStruct { private int x; public int ChangeInternal() { this.x = this.x + 1; return this.x; } } 

When I run this code, it gives me 1, 1, 1, but when I delete "readonly", it says 1, 2, 3.

Can someone explain this to me?

+6
source share
1 answer

Section 7.5.4 of the C # specs states:

[...] if the field is readonly, and the link occurs outside the constructor of the instance of the class in which the field is declared, then the result is a value, namely the value of the field i in the object referenced by E

So, when the field is readonly , you mutate the copy (since it is impossible to change the value, but only the variable). When this is not the case, you mutate the field itself.

This is described in more detail in this Eric Lippert blog post . To quote its ending:

This is another reason why mutable value types are evil. Try to always make value types immutable.

+5
source

Source: https://habr.com/ru/post/977674/


All Articles