Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutability of structs [duplicate]

Possible Duplicate:
Why are mutable structs evil?

I read it in lots of places including here that it's better to make structs as immutable.

What's the reason behind this? I see lots of Microsoft-created structs that are mutable, like the ones in xna. Probably there are many more in the BCL.

What are the pros and cons of not following this guideline?

like image 662
Joan Venge Avatar asked Mar 03 '09 22:03

Joan Venge


People also ask

Are structs immutable?

Yep, you're right, structs are not immutable. The thing about structs is that they are values. That means every variable is considered a copy, and its members are isolated from changes made to other variables. Structs are not copied on mutation.

Why should struct be immutable?

Creating mutable structs can lead to all kinds of strange behavior in your application and, therefore, they are considered a very bad idea (stemming from the fact that they look like a reference type but are actually a value type and will be copied whenever you pass them around).

Why are structs immutable C#?

It's a good idea to make struct immutable, it means once it is initalized, it cannot be modified. System. DateTime is an immutable Value Type. It provides many static methods but it always returns a new instance.

Are structs immutable in Golang?

After an object (or struct) is created, it can never be changed. It's immutable.


1 Answers

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.

like image 174
Marc Gravell Avatar answered Oct 13 '22 08:10

Marc Gravell