C# 7.2 introduces the ability to make struct
declaration readonly
.
What does this do?
The readonly
modifier on a struct
definition declares that the struct is immutable. the Every instance field of the struct
must be marked readonly
, as shown in the following example:
It guarantees that no member of the struct can manipulate its content as it ensures every field is marked as readonly
. Adding a field not marked as readonly will generate the following compiler error:
CS8340
: "Instance fields of readonly structs must be readonly."
This guarantee is important because it allows the compiler to avoid defensive copies of struct
values. For example when invoking members of a struct
which is stored in a readonly
field(like the ToString() method in the example above). Invocations like the ToString
now occur directly on the field, avoiding the wasteful copy it had to do before.
You can even go one step further by using readonly auto properties. That instructs the compiler to create readonly
backing fields for those properties. If we rewrite the code above, it becomes: