Before C# 9, to make a property immutable, you had to use constructor injection. This broke object initializers (`new Obj { Prop = val }`). The `init` accessor solves this by allowing setting a property only during object initialization.
The ‘init’ Keyword
public class User
{
public string Id { get; init; } // Can only be set during construction
public string Username { get; set; } // Mutable
}
// Valid
var user = new User
{
Id = "123",
Username = "nitrix"
};
// Invalid - Compiler Error
user.Id = "456";
Why this matters for DTOs
It allows for consistent, valid state without massive constructors.
Key Takeaways
- Replace `private set` with `init` for properties that shouldn’t change after creation.
- Works perfect with serialized data (JSON deserializers can set init properties).
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.