C# 9.0 Init-Only Setters: Immutable Object Initialization

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.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.