ADocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
readonly struct is a value type declared with the readonly modifier, which enforces strict immutability at the compiler level. When applied to a struct, the C# compiler guarantees that the state of the object cannot be modified after initialization, treating the hidden this reference as an in parameter for all instance members.
Compiler Rules and Constraints
Applying thereadonly modifier to a struct imposes the following strict compilation rules:
- Instance Fields: Every instance field declared within the struct must be explicitly marked with the
readonlykeyword. - Properties: Auto-implemented properties cannot have
setaccessors. They must be get-only or utilizeinitaccessors. - Constructors: As of C# 11, struct constructors no longer require explicit definite assignment of all fields before control leaves the constructor. The compiler automatically initializes any unassigned fields to their default values.
- Events: Field-like events are prohibited because the compiler automatically generates a mutable backing delegate field for them. To implement events in a
readonly struct, you must explicitly define customaddandremoveaccessors. - Static Members: The
readonlyconstraint applies exclusively to instance state. Static fields and static properties within areadonly structare not required to be readonly.
Mechanics of the this Reference
In a standard, non-readonly struct, the compiler passes the this reference to instance methods and property accessors as a ref parameter. This allows instance methods to mutate the struct’s internal state.
In a readonly struct, the compiler alters the method signature of all instance members to pass the this reference as an in parameter (ref readonly).
this is an in parameter, the compiler statically guarantees that no instance method can mutate the struct. Consequently, if a readonly struct is passed to another method via the in modifier, the compiler will not generate hidden defensive copies when invoking its instance members, as the immutability is already guaranteed at the type level.
Compilation Failures
Attempting to violate the immutability contract results in immediate compiler errors:Master C# with Deep Grasping Methodology!Learn More





