I have a struct, MyStruct
, that has a private member private bool[] boolArray;
and a method ChangeBoolValue(int index, bool Value)
. <
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