.net - C# Struct method doesn't save value if accessed by a property -
i need create structure looks int (but has field need...), created new structure named teststruct added 1 method (test()) needed , overloaded operators, , seemed working well...
the sample below shows problem. if structure test() method executed val property val property seems lose value, if method executed on val2 variable, 1 seems keep right value...
why happen?
static class program { /// <summary> /// main entry point application. /// </summary> [stathread] static void main() { new testclass(); } } public class testclass { public teststruct val { get; set; } private teststruct val2; public testclass() { val.test(); console.writeline(val + "-> why not 10?"); //direct assignment works well... val = 123; console.writeline(val + "-> direct assingment works.."); //this way works too. why doesn't work "get;" , "set;"? val2.test(); console.writeline(val2 + "-> works way"); } } public struct teststruct { private int32 _value; public long offset { get; set; } public static implicit operator teststruct(int32 value) { return new teststruct { _value = value }; } public static implicit operator int32(teststruct value) { return value._value; } public void test() { _value = 10; } }
your struct
wrong.
for large number of reasons, should never make mutable struct.
just int
or datetime
value immutable , can never change, specific value of struct
must never change @ all.
instead, can make functions return new, different value .
here reasons mutable structs evil:
- http://ericlippert.com/2008/05/14/mutating-readonly-structs/
- http://blog.slaks.net/2010/12/when-shouldnt-you-write-ref-this.html
- http://codeblog.jonskeet.uk/2010/07/27/iterate-damn-you/
- http://philosopherdeveloper.wordpress.com/2011/03/31/how-i-discovered-a-bug-in-the-c-compiler-part-1/
to answer question, val.test()
equivalent get_val().test()
.
since structs value types, `get_val() (the automatically-generated property getter) returns copy of struct.
original struct in private backing field not affected.
Comments
Post a Comment