Init-only setters
Init-only setters (C# 9.0+) allow a property to be assigned a value only during object initialization, either in the constructor or with an object initializer. After initialization, the property is effectively read-only.
Line 3 is the init-only property, and line 4 is a regular settable one. Line 10 is the error you get from assigning the init-only property after initialization.
C#
public class Customer{ public int Id { get; init; } // Can only be set during initialization public string Name { get; set; } // Regular settable property public Customer(int id) { Id = id; } // Set in constructor}// var cust = new Customer(1) { Name = "Contoso" }; // Id can be set via constructor// cust.Name = "Contoso Inc."; // OK// cust.Id = 2; // Error: Init-only property can only be assigned in an object initializer, // or on 'this' or 'base' in an instance constructor or 'init' accessor.Where it matters
Init-only setters make it easier to create immutable objects. Properties can be set flexibly at the point of creation, while it’s guaranteed they can’t be changed later. They work very well with recordsRecordsA class for immutable data, with value-based equality generated for you.Opens in a new tab and support the trend toward more immutable data structures.
Sources
- milanm/csharp-cheatsheet, GitHub · accessed May 16, 2025