Immutability with init & with
Use init-only setters to create immutable objects and with-expressions to produce non-destructively modified copies.
What Is Immutability?
An immutable object cannot be changed after creation. Immutability prevents accidental mutation, makes objects thread-safe by default, and simplifies reasoning about code. C# provides init setters and with expressions to make immutability ergonomic.
init-Only Setters
An init accessor allows a property to be set during object initialization (constructor or object initializer) but never after. It's the immutable counterpart to set.
public class Point
{
public double X { get; init; }
public double Y { get; init; }
}
var p = new Point { X = 3.0, Y = 4.0 }; // OK — init phase
p.X = 5.0; // COMPILE ERROR — cannot set after init
// All of these are valid init-phase assignments:
var p2 = new Point(X: 1.0, Y: 2.0);
var p3 = new Point { X = 0, Y = 0 };All lessons in this course
- Record Types: Basics & Syntax
- Immutability with init & with
- Value Equality & Deconstruction
- Records in Domain-Driven Design