init accessor
A property accessor written init instead of set, which allows the value to be assigned only while the object is being created.
In more detail
An object initialiser can set it once; nothing can change it afterwards, which makes the property effectively immutable. Records use init accessors for their positional properties.
Example
public Guid Id { get; init; } = Guid.NewGuid();Related terms
- property — A named value belonging to an object; in languages such as C# and Python, it can also be a member that looks like a field but runs code when read or written.
- object initializer — C# syntax that sets properties in braces right after new, such as new Product { Name = "Kettle", Price = 24.50m }.
- immutable — Something that cannot be changed after it is created; to change it you make a new one.
- record — A C# type declared with the record keyword for data, for which the compiler generates a constructor, properties, value equality, a readable ToString and with-expression copying.
Taught in
- Classes, Interfaces, and Object-Oriented C# — Modern .NET Core, C# & Enterprise Microservices
- Records, Pattern Matching, and Modern C# — Modern .NET Core, C# & Enterprise Microservices