×

c# · level 3 · unit 5 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Immutable objects cannot change after they are made.

An immutable object is fixed once built. Nobody can change it behind your back, threads can share it safely, and no bug comes from someone quietly editing it. To change something, make a new copy, as records do with with.

Write instead of { get; set; }. An init accessor accepts a value while the object is being created, then locks: a later assignment will not compile. Positional records already work this way.

A list inside is still an open door. Take a when the object is built, and expose it as IReadOnlyList<T>, which has no Add or Remove.

using System;
using System.Collections.Generic;

var stops = new List<string> { "Leeds", "York" };
var route = new Route("Express", stops);
stops.Add("Hull");
Console.WriteLine($"{route.Name}: {string.Join(" > ", route.Stops)}");
var late = route with { Name = "Late express" };
Console.WriteLine($"{late.Name}: {late.Stops.Count} stops");

record Route
{
    public string Name { get; init; }
    public IReadOnlyList<string> Stops { get; init; }

    public Route(string name, List<string> stops)
    {
        Name = name;
        Stops = new List<string>(stops);
    }
}

A readonly field works like init for fields: it can only be set while the object is being built.