I have a struct, MyStruct
, that has a private member private bool[] boolArray;
and a method ChangeBoolValue(int index, bool Value)
.
I have a class, MyClass
, that has a field public MyStruct bools { get; private set; }
When I create a new MyStruct object from an existing one, and then apply method ChangeBoolValue(), the bool array in both objects is changed, because the reference, not what was referred to, was copied to the new object. E.g:
MyStruct A = new MyStruct();
MyStruct B = A; //Copy of A made
B.ChangeBoolValue(0,true);
//Now A.BoolArr[0] == B.BoolArr[0] == true
Is there a way of forcing a copy to implement a deeper copy, or is there a way to implement this that will not have the same issue?
I had specifically made MyStruct a struct because it was value type, and I did not want references propagating.
The runtime performs a fast memory copy of structs and as far as I know, it's not possible to introduce or force your own copying procedure for them. You could introduce your own Clone
method or even a copy-constructor, but you could not enforce that they use them.
Your best bet, if possible, to make your struct immutable (or an immutable class) or redesign in general to avoid this issue. If you are the sole consumer of the API, then perhaps you can just remain extra vigilant.
Jon Skeet (and others) have described this issue and although there can be exceptions, generally speaking: mutable structs are evil. Can structs contain fields of reference types