đź”’ Set Once, Never Change
Readonly properties need constructor. Init only setters allow object initializer syntax. Immutable after creation, no constructor boilerplate.
❌ Before (Constructor Boilerplate)
public class Person
{
public string Name { get; }
public int Age { get; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
var p = new Person("Alice", 30);
âś… Init Only Setters
public class Person
{
public string Name { get; init; }
public int Age { get; init; }
}
var p = new Person { Name = "Alice", Age = 30 };
// p.Name = "Bob"; // Error! Cannot modify
🎯 Advanced Init Usage
// With validation
public class User
{
private string _email;
public string Email
{
get => _email;
init
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("Email required");
if (!value.Contains('@'))
throw new ArgumentException("Invalid email");
_email = value;
}
}
public string Name { get; init; }
public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
}
// With records (records use init by default)
public record Product(string Name, decimal Price);
// Inheritance with init
public class Employee : Person
{
public string Department { get; init; }
}
đź’ˇ Benefits
- Immutable objects without constructor boilerplate
- Object initializer syntax (clean and readable)
- Validation in init setter
- Perfect for DTOs, configuration, value objects
- Works with required keyword (C# 11)
“Hated writing constructors for immutable DTOs. Init-only setters fixed that. Object initializer syntax works, object stays immutable. Best of both worlds.”
