Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are mutable structs “evil”?

Following the discussions here on SO I already read several times the remark that mutable structs are “evil” (like in the answer to this question).

What's the actual problem with mutability and structs in C#?

like image 883
Dirk Vollmar Avatar asked Jan 13 '09 23:01

Dirk Vollmar


People also ask

What does it mean that structs are 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. They may be mutated in-place.

How do you make a struct immutable?

To make a struct immutable, the simple way to make all the members readonly and initializ these values via parameterized constructor. It's members should be exposed via getter fields. Above struct is immutable as there is no way to modify the initialized variable.

What is mutable class in C#?

Mutable type, in C#, is a type of object whose data members, such as properties, data and fields, can be modified after its creation. Mutable types are used in parallel applications, where the objects of mutable value type are maintained in the stack by the Common Language Runtime (CLR).

What is a ref struct?

What is a ref struct? Well, a ref struct is basically a struct that can only live on the stack. Now a common misconception is that since classes are reference types, those live on the heap and structs are value types and those live on the stack.


1 Answers

Structs are value types which means they are copied when they are passed around.

So if you change a copy you are changing only that copy, not the original and not any other copies which might be around.

If your struct is immutable then all automatic copies resulting from being passed by value will be the same.

If you want to change it you have to consciously do it by creating a new instance of the struct with the modified data. (not a copy)

like image 193
trampster Avatar answered Sep 29 '22 23:09

trampster