An init-only property is a property that restricts assignment to the phase of object construction. By replacing the standardDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
set accessor with the init keyword, the C# compiler enforces immutability for that property once the initialization phase completes.
The Initialization Phase
The C# compiler defines a strict window during which aninit accessor can be invoked. Assignment is exclusively permitted in the following contexts:
- Object Initializers: During the instantiation of the object using curly brace syntax.
- Constructors: Within the constructor of the declaring type or a derived type.
- Inline Initializers: At the point of property declaration.
withExpressions: During non-destructive mutation to create a new instance.- Other
initAccessors: Within the body of anotherinitaccessor on the same instance.
init property outside this phase results in compiler error CS8852.
Explicit Implementation and Readonly Backing Fields
When manually implementing aninit accessor rather than using an auto-implemented property, the accessor is granted special compiler privileges to mutate readonly backing fields. This mirrors the behavior of a constructor.
Interaction with with Expressions
Init-only properties are foundational to non-destructive mutation in C#. When a with expression is evaluated, the compiler creates a clone of the original object and then executes the init accessors for the properties specified in the initializer block.
Type Compatibility
Theinit accessor is a feature of the property system itself, not tied to a specific type category. It is fully supported across:
classstructrecord(Positional properties are compiled asget; init;forrecord classandreadonly record struct. However, positional properties in a standardrecord structare compiled asget; set;)interface(Interfaces can declareinitaccessors to enforce initialization contracts on implementing types)
Master C# with Deep Grasping Methodology!Learn More





