Immutable Object Patterns
Design objects that never change after creation.
Designing Immutable Objects
An immutable object never changes after construction. Immutability removes whole classes of bugs around shared mutable state and makes objects safe to pass around and cache.
Get-Only Properties
The simplest immutable property is get-only, assigned once from a constructor.
using System;
class Point {
public int X { get; }
public int Y { get; }
public Point(int x, int y) { X = x; Y = y; }
}
var p = new Point(3, 4);
Console.WriteLine(p.X + "," + p.Y); // 3,4All lessons in this course
- init-Only Setters
- The required Modifier
- Immutable Object Patterns
- with Expressions on Records