DEV Community

loading...

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

baenencalin profile image Calin Baenen ・1 min read

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!

Discussion (7)

pic
Editor guide
Collapse
lifelongthinker profile image
Sebastian

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!

Collapse
baenencalin profile image
Calin Baenen Author

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.

Collapse
lifelongthinker profile image
Sebastian

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.

Thread Thread
lifelongthinker profile image
Sebastian

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".

Thread Thread
baenencalin profile image
Calin Baenen Author

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

Thread Thread
lifelongthinker profile image
Sebastian

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.

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...