C# Academy · Lesson

Immutable Object Patterns

Design objects that never change after creation.

Lesson 3 of 413 steps

Immutable Object Patterns is a free C# Academy lesson on CoddyKit. This is lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, and your progress syncs across the web and the CoddyKit app. The C# Academy course includes 4 lessons in total.

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

init for Initializer Syntax

Use init properties when you want immutability plus the convenient object-initializer syntax.

using System;

class Color {
    public int R { get; init; }
    public int G { get; init; }
    public int B { get; init; }
}

var c = new Color { R = 255, G = 128, B = 0 };
Console.WriteLine(c.R + "," + c.G + "," + c.B); // 255,128,0

required for Mandatory Fields

Combine required + init so essential fields cannot be forgotten and cannot change.

using System;

class Money {
    public required decimal Amount { get; init; }
    public required string Currency { get; init; }
}

var m = new Money { Amount = 9.99m, Currency = "USD" };
Console.WriteLine(m.Amount + " " + m.Currency); // 9.99 USD

Returning New Objects Instead of Mutating

Immutable types expose "change" operations as methods that return a new instance, leaving the original untouched.

using System;

class Point {
    public int X { get; init; }
    public int Y { get; init; }
    public Point Move(int dx, int dy) => new Point { X = X + dx, Y = Y + dy };
}

var a = new Point { X = 1, Y = 1 };
var b = a.Move(2, 3);
Console.WriteLine(a.X + "," + a.Y + " -> " + b.X + "," + b.Y); // 1,1 -> 3,4

Immutable Collections

For collection fields, store an immutable or read-only collection so the contents cannot be mutated through the object.

using System;
using System.Collections.Immutable;

class Team {
    public ImmutableList<string> Members { get; init; } = ImmutableList<string>.Empty;
}

var t = new Team { Members = ["Ada", "Lin"] };
var t2 = new Team { Members = t.Members.Add("Sam") };
Console.WriteLine(t.Members.Count + " " + t2.Members.Count); // 2 3

Defensive Copying

If you must accept a mutable collection, copy it on the way in so external changes cannot leak through.

using System;
using System.Collections.Generic;
using System.Linq;

class Snapshot {
    private readonly int[] data;
    public Snapshot(IEnumerable<int> source) => data = source.ToArray();
    public IReadOnlyList<int> Data => data;
}

var list = new List<int> { 1, 2, 3 };
var snap = new Snapshot(list);
list.Add(4); // does not affect snap
Console.WriteLine(snap.Data.Count); // 3

Value Equality

Immutable objects often want value-based equality: two instances with the same data are considered equal. Records give this for free; classes need overrides.

using System;

record Coord(int X, int Y);

Console.WriteLine(new Coord(1, 2) == new Coord(1, 2)); // True

Thread Safety for Free

Because immutable objects never change, they are inherently thread-safe to share without locks.

using System;

class ReadonlyConfig {
    public required string Env { get; init; }
}

var cfg = new ReadonlyConfig { Env = "prod" };
// safe to read from many threads without synchronization
Console.WriteLine(cfg.Env); // prod

readonly Fields and structs

Use readonly fields and readonly struct to enforce immutability for value types at the field level.

using System;

readonly struct Vector {
    public readonly double X, Y;
    public Vector(double x, double y) { X = x; Y = y; }
    public double Length => Math.Sqrt(X * X + Y * Y);
}

Console.WriteLine(new Vector(3, 4).Length); // 5

Putting It Together

A fully immutable type combining required, init, value equality, and a non-mutating update method.

using System;

record Account(string Id, decimal Balance) {
    public Account Deposit(decimal amount) => this with { Balance = Balance + amount };
}

var a = new Account("A1", 100m);
var b = a.Deposit(50m);
Console.WriteLine(a.Balance + " -> " + b.Balance); // 100 -> 150

Quick Check

Confirm the immutable-update principle.

Recap

You learned patterns for immutable objects.

  • Use get-only or init properties and required for mandatory data.
  • Model changes as methods returning new instances.
  • Store immutable or defensively-copied collections.
  • Records provide value equality and with copies; immutability gives thread safety.
Free to start

Learn C# with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
93
Lessons
346

Frequently Asked Questions

Is the “Immutable Object Patterns” lesson free?

Yes — the full text of “Immutable Object Patterns” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO. The C# Academy course includes 4 lessons in total.

What will I learn in “Immutable Object Patterns”?

Design objects that never change after creation. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Immutable Object Patterns” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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