c# - How to ensure a struct with a string array as a field would follow value semantics while assigning to another variable -
in msdn documentation mentioned "structs copied on assignment. when struct assigned new variable, data copied, , modification new copy not change data original copy."
i have struct has string array field inside it.
struct myvar { private readonly string[] value; myvar(string[] ival) { value = ival; } }
when assign 1 struct variable how ensure string array copied (deep copy) assigned variable.
you can't in c# because there's no way intercept compiler-generated code copy struct's data 1 another.
the thing can make struct immutable.
that means:
- when create struct, make defensive copy of mutable reference types store inside struct (such string array in example).
- do not pass mutable reference type objects can mutate them.
- do not expose mutable reference types struct. mean couldn't expose string array struct.
- don't mutate reference types held in struct. in example, couldn't change contents of string array.
that's lot of limitations. safest way never store mutable reference types in struct...
anyway, make struct safer can defensively copy string array:
struct myvar { private readonly string[] value; myvar(string[] ival) { value = (string[])ival.clone(); } }
that particular example safe copy because doesn't have way string array mutated. add mutator methods or expose string array via property, or pass might mutate it, you're square one.
if want make "manual" copy of struct though, can via serialization.
it's can't about:
myvar var1 = new myvar(test); myvar var2 = var1;
Comments
Post a Comment