DEV Community

Calin Baenen
Calin Baenen

Posted on

What's the point of a `readonly struct` if the types aren't implicitly made `readonly`?

What's the difference between a struct with ALL readonly fields, and a readonly struct, which requires you to explicitly state all fields as readonly?
This just seems like an extra KW for no reason, if it's not implicitly making things readonly.

Thanks!
Cheers!

Top comments (3)

Collapse
 
mileswatson profile image
Miles Watson • Edited

It makes it clearer to other programmers that they shouldn’t try and add mutable fields. It also has the added benefit of allowing better compiler optimisation. I would recommend using a record as opposed to a read only struct in most situations.

docs.microsoft.com/en-us/dotnet/st...

Collapse
 
baenencalin profile image
Calin Baenen

Why doesn't it just implicitly make everything readonly for me, then?
Surely it would be thought through that having a bunch of readonlys, or {get;}s in a struct that has already been declared readonly is kind of redundant, and (in my opinion) ugly.

 
baenencalin profile image
Calin Baenen

Huh? But isn't readonly like final (from Java)???
I think I'm confused.