Immutability of structs [duplicate]

Structs should represent values. Values do not change. The number 12 is eternal.

However, consider:

Foo foo = new Foo(); // a mutable struct
foo.Bar = 27;
Foo foo2 = foo;
foo2.Bar = 55;

Now foo.Bar and foo2.Bar is different, which is often unexpected. Especially in the scenarios like properties (fortunately the compiler detect this). But also collections etc; how do you ever mutate them sensibly?

Data loss is far too easy with mutable structs.

Leave a Comment