Init-Only Setters (`init`), `required` Keyword & Object Initializers
1Concept
`init` accessors allow property mutation only during object construction. The `required` keyword forces callers to initialize specified properties in object initializers at compile-time.
2Architecture Diagram
Caller Construction:
var config = new ServerConfig { Host = "localhost", Port = 8080 }; // OK
config.Port = 9000; // COMPILE ERROR: init-only property cannot be mutated after construction!3Code Example
C# 13 & .NET 9
using System;
public class ServerConfig
{
public required string Host { get; init; }
public required int Port { get; init; }
public bool EnableSsl { get; init; } = true;
}
public class InitOnlyDemo
{
public static void Main()
{
var cfg = new ServerConfig
{
Host = "api.enterprise.cloud",
Port = 443
};
Console.WriteLine($"Server: {cfg.Host}:{cfg.Port} (SSL: {cfg.EnableSsl})");
}
}4Expected Output
Server: api.enterprise.cloud:443 (SSL: True)
5Key Takeaways
- ✓`init` enables clean object initializers while maintaining immutability.
- ✓`required` guarantees that critical properties are never omitted during instantiation.
- ✓Combine with `[SetsRequiredMembers]` for custom constructor overloads.