C# 9.0 Init-Only Setters: Immutable Object Initialization

On this page

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

C#15 lines
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.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

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.