Wednesday, 15 January 2014

c# - readonly changing the behavior of a struct -



c# - readonly changing the behavior of a struct -

i'm trying understand basic concepts:

class programme { 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; homecoming this.x; } }

when run code gives me 1, 1, 1, when remove "readonly" says 1, 2, 3.

can explain me this?

section 7.5.4 of c# specs states:

[...] if field readonly , reference occurs outside instance constructor of class in field declared, result value, namely value of field in object referenced e

so when field readonly you're mutating re-create (since it's impossible mutate value, variable). when isn't you're mutating field itself.

this described in more detail in this blog post eric lippert. quote ending:

this yet reason why mutable value types evil. seek create value types immutable.

c# immutability readonly

No comments:

Post a Comment