0Pricing
C# Academy · Lesson

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,4

All lessons in this course

  1. init-Only Setters
  2. The required Modifier
  3. Immutable Object Patterns
  4. with Expressions on Records
← Back to C# Academy