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!
Cheers!
Discussion (7)
The difference lies in your intention.
The read-only struct is intended to be immutable, so the compiler will enforce that any future properties and fields be declared read-only.
The non-read-only struct with all read-only properties and members could at some point be modified to contain a non-read-only member, essentially making it a mutable struct.
Mutable vs. immutable, of course, also have practical run-time implications (performance).
Intention is a very important design decision!
Why doesn't it just implicitly make everything
readonly
for me, then?Surely it would be thought through that having a bunch of
readonly
s, or{get;}
s in astruct
that has already been declaredreadonly
is kind of redundant, and (in my opinion) ugly.It's not redundant. Because you could also have the case where all members/properties are declared read-only but the type itself is not supposed to be read-only and thus should be open to be mutable in the future. This intent should not be lost.
Again, such a decision also has run-time implications because the compiler can optimize.
For such and similar questions, I highly recommend Albahari's "C# in a Nutshell".
Huh? But isn't readonly like
final
(from Java)???I think I'm confused.
I'm not eloquent in Java enough to give you a reliable answer, but the read-only modifier has a lot in common with Java's final. I'm just not sure about Java's semantics with final and value types.
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...