c# - Setting Property Doesn't Set Its Inner Property -


i took address: http://csharpindepth.com/articles/chapter8/propertiesmatter.aspx , reason not head around it. can explain me why console.writeline(holder.property.value); outputs 0.

void main() {     mutablestructholder holder = new mutablestructholder();     holder.field.setvalue(10);     holder.property.setvalue(10);     console.writeline(holder.field.value); // outputs 10     console.writeline(holder.property.value); // outputs 0 }  struct mutablestruct {     public int value { get; set; }      public void setvalue(int newvalue)     {         value = newvalue;     } }  class mutablestructholder {     public mutablestruct field;     public mutablestruct property { get; set; } } 

class mutablestructholder {     public mutablestruct field;     public mutablestruct property { get; set; } } 

is equivalent

class mutablestructholder {     public mutablestruct field;      private mutablestruct _property;     public mutablestruct property {         { return _property; }        set { _property = value; }     } } 

which equivalent to:

class mutablestructholder {     public mutablestruct field;      private mutablestruct _property;     public mutablestruct getproperty() {         return _property;     }     public void setproperty(mutablestruct value) {         _property = value;     } } 

so, when this:

holder.property.setvalue(10); 

you're doing this:

holder.getproperty().setvalue(10); 

which equivalent to:

mutablestruct temp = holder.getproperty();  temp.setvalue(10); 

and because structs value types, temp copy of underlying _property field, , modification thrown away when goes out of scope (immediately).

this reason avoid mutable structs plague.


Comments

Popular posts from this blog

How to access named pipes using JavaScript in Firefox add-on? -

multithreading - OPAL (Open Phone Abstraction Library) Transport not terminated when reattaching thread? -

node.js - req param returns an empty array -