Records: The Immutable Stamp

Records: The Immutable Stamp in C#: Nobody edits a receipt. If the till got the price wrong, the shop does not fetch a pen and scribble over the total — it…

The Analogy: The Printed Receipt

Nobody edits a receipt. If the till got the price wrong, the shop does not fetch a pen and scribble over the total — it voids the receipt and prints a new one. The old slip stays exactly as it was printed, which is the entire point: it is evidence, and evidence you can quietly amend is worthless.

Two receipts for the same items at the same prices are also the same receipt, for every purpose that matters, even though they are two pieces of paper. You compare them by reading them, not by checking whether they are physically the same slip.

That is a record: a type whose identity is what it contains rather than which object it happens to be, and which you change by printing a new one rather than editing the old. Classes are the opposite on both counts — two BankAccount objects with identical balances are still two different accounts, and you change one by assigning to its properties.

Choosing between them is one question: if two of these have all the same values, are they the same thing? Money, a coordinate, a date range, an API response — yes. A user session, a bank account, a shopping cart — no.


Syntax or Core Structure

using System;
using System.Collections.Generic;

record Person(string First, string Last, int Age);       // positional: one line, done

record Address                                          // a record with a body
{
    public required string City { get; init; }
    public string Postcode { get; init; } = "";
    public string Full => $"{City} {Postcode}".Trim();
}

readonly record struct Point(int X, int Y);              // a value type, no allocation

class Program
{
    static void Main()
    {
        var a = new Person("Ada", "Lovelace", 36);
        var b = new Person("Ada", "Lovelace", 36);

        Console.WriteLine(a);                             // ToString you did not write
        Console.WriteLine($"a == b: {a == b}, ReferenceEquals: {ReferenceEquals(a, b)}");
        Console.WriteLine($"same hash: {a.GetHashCode() == b.GetHashCode()}");

        Person older = a with { Age = 37 };                // copy, changing one thing
        Console.WriteLine($"{older.First} is now {older.Age}, a is still {a.Age}");

        var (first, last, age) = a;                        // Deconstruct, also free
        Console.WriteLine($"destructured: {first} {last} {age}");

        var home = new Address { City = "Bath", Postcode = "BA1 1AA" };
        Console.WriteLine($"address: {home.Full}");
        // home.City = "Bristol";                          // CS8852: init-only

        Point p = new(3, 4);
        Point q = p with { Y = 9 };
        Console.WriteLine($"{p} -> {q}, equal: {p == q}");

        var seen = new HashSet<Person> { a, b };           // value equality: b is a duplicate
        Console.WriteLine($"distinct people: {seen.Count}");
    }
}

Output:

Person { First = Ada, Last = Lovelace, Age = 36 }
a == b: True, ReferenceEquals: False
same hash: True
Ada is now 37, a is still 36
destructured: Ada Lovelace 36
address: Bath BA1 1AA
Point { X = 3, Y = 4 } -> Point { X = 3, Y = 9 }, equal: False
distinct people: 1

Count what record Person(string First, string Last, int Age); bought: a constructor, three properties, a readable ToString, value-based Equals, a matching GetHashCode, == and !=, Deconstruct, and the copy machinery behind with. In the classes lesson that was about sixty lines of boilerplate — and the hand-written GetHashCode was the line most likely to be wrong.


Technical Depth: What record Generates, and What It Does Not

The generated members

For record Person(string First, string Last, int Age) the compiler emits:

MemberDetail
A primary constructorpositional parameters, in order
Three { get; init; } propertiessettable during construction only
ToString()Person { First = Ada, ... }, via a PrintMembers hook you can override
Equals(Person?) and Equals(object?)field-by-field, plus a runtime-type check
GetHashCode()combined from every field
== and !=value comparison, unlike a class
Deconstruct(out ...)positional records only
A protected copy constructor and Clonewhat with calls

You may replace any of them by declaring your own. Adding public override string ToString() => ... simply wins.

record class, record struct, class, struct

classrecord classstructreadonly record struct
Equalityreferencevaluevalue (slow, reflective)value, fast
== comparesreferencescontentsnot defined by defaultcontents
Allocationheapheapinline / stackinline / stack
with supportnoyesyes (record struct)yes
Members immutable by defaultnoinit-onlynoyes
Inheritanceyesyes, from records onlynono

record alone means record class. One trap: a plain record struct's positional properties are { get; set; } — mutable. Write readonly record struct and they become { get; init; }, which is what you almost always want.

with is a shallow copy

This is the sharpest edge on the whole feature:

record Team(string Name, List<string> Members);

var a = new Team("core", new List<string> { "ada" });
var b = a with { Name = "core-2" };

b.Members.Add("grace");
Console.WriteLine($"{a.Members.Count} {b.Members.Count}");    // 2 2 - the SAME list
Console.WriteLine(a == b);                                    // False: only Name differs

with copies fields, and a field holding a reference is copied as a reference. A record is only as immutable as the things inside it. Hold IReadOnlyList<T> or ImmutableArray<T>, and copy explicitly when you mean to.

The same shallowness affects equality: two records holding different List<string> instances with identical contents are not equal, because List<T> compares by reference. Use ImmutableArray<T> with a structural comparer, or override Equals and use SequenceEqual.

Inheritance and the equality contract

record Employee(string Name, decimal Salary);
record Manager(string Name, decimal Salary, int Reports) : Employee(Name, Salary);

Employee e = new Employee("Grace", 7000m);
Employee m = new Manager("Grace", 7000m, 3);
Console.WriteLine(e == m);        // False - and it would be False even with equal fields

Records compare a hidden EqualityContract (the runtime type) before anything else, so a base and a derived record are never equal. That is the correct answer, and it is one more thing you would have got wrong by hand. Note also that a record may only inherit from another record, and a class may not inherit from a record.

Validation in a positional record

Positional parameters are not properties you can guard directly, but two idioms work:

record Reading(string Sensor, double Value)
{
    public string Sensor { get; init; } =
        string.IsNullOrWhiteSpace(Sensor) ? throw new ArgumentException("sensor required") : Sensor;
}

record Span                                             // body form, explicit constructor
{
    public Span(int low, int high)
    {
        if (high < low) throw new ArgumentException("high must not be below low");
        Low = low;
        High = high;
    }

    public int Low { get; init; }
    public int High { get; init; }
}

The first form — re-declaring the property with a validating initialiser — keeps the one-line positional syntax. The second is what you write when the rule spans two parameters, because a property initialiser can only see its own.

init versus set versus readonly

init accessors run during construction and object initialisers, then lock. That is what makes with possible: the copy constructor runs, then the initialiser assigns the changed members, then the object is frozen. A readonly field could not be assigned in that second step; a set would leave the object mutable forever.

Where records earn their keep

DTOs and API contracts, messages and events, value objects (Money, Sku, DateRange), query results, and dictionary or HashSet keys — a record is a correct key for free, which last lesson's warning about mutable keys should make you appreciate. They also pair perfectly with the deconstruction and positional patterns in the next lesson, which is not a coincidence: both features shipped for the same style of code.

Where they do not fit: entities with identity and a lifecycle. An EF Core entity, a UI view model with two-way binding, anything you mutate in place. Reaching for a record there means fighting init all day.


Real World Example: An Order History You Cannot Falsify

An order that moves from draft to shipped can be modelled two ways. Mutate one object and lose the past, or keep a list of snapshots where each one is the previous one plus a change. Records make the second way the easy way.

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

readonly record struct Money(decimal Amount, string Currency)
{
    public override string ToString() => $"{Amount:F2} {Currency}";

    public static Money operator +(Money a, Money b) =>
        a.Currency == b.Currency
            ? new Money(a.Amount + b.Amount, a.Currency)
            : throw new InvalidOperationException("currency mismatch");
}

record OrderLine(string Sku, int Quantity, Money UnitPrice);

record Order(string Id, string Status, IReadOnlyList<OrderLine> Lines)
{
    public Money Total => Lines.Aggregate(
        new Money(0m, "GBP"),
        (sum, l) => sum + new Money(l.UnitPrice.Amount * l.Quantity, l.UnitPrice.Currency));
}

class Program
{
    static void Main()
    {
        var order = new Order("SO-77", "draft", new List<OrderLine>
        {
            new("mug", 2, new Money(7.50m, "GBP")),
            new("tee", 1, new Money(18.00m, "GBP"))
        });

        var history = new List<Order> { order };

        history.Add(history[^1] with { Status = "placed" });
        history.Add(history[^1] with
        {
            Status = "amended",
            Lines = history[^1].Lines.Append(new OrderLine("cap", 3, new Money(9.20m, "GBP"))).ToList()
        });
        history.Add(history[^1] with { Status = "shipped" });

        foreach (Order snapshot in history)
            Console.WriteLine($"{snapshot.Status,-8} {snapshot.Lines.Count} lines  {snapshot.Total}");

        Console.WriteLine($"draft total still {history[0].Total}");
        Console.WriteLine($"same lines object in first two snapshots: {ReferenceEquals(history[0].Lines, history[1].Lines)}");
        Console.WriteLine($"placed == draft: {history[1] == history[0]}");
        Console.WriteLine($"reprint equal: {(history[0] with { Status = "draft" }) == history[0]}");

        var prices = new Dictionary<Money, string>          // a record struct as a key
        {
            [new Money(7.50m, "GBP")] = "mug",
            [new Money(18.00m, "GBP")] = "tee"
        };
        Console.WriteLine($"7.50 GBP is the {prices[new Money(7.50m, "GBP")]} price");
    }
}

Output:

draft    2 lines  33.00 GBP
placed   2 lines  33.00 GBP
amended  3 lines  60.60 GBP
shipped  3 lines  60.60 GBP
draft total still 33.00 GBP
same lines object in first two snapshots: True
placed == draft: False
reprint equal: True

The draft still totals 33.00 after two amendments, because nothing was ever edited — four with expressions produced four independent snapshots. reprint equal: True shows the flip side: a copy that changes nothing is equal to the original, which is exactly the receipt rule.

The True on the third line is the shallow-copy warning made concrete: snapshots one and two share the same List<OrderLine> instance. Here it is harmless because nobody mutates it — the third snapshot built a new list rather than calling Add. In production you would hold ImmutableArray<OrderLine> so that "nobody mutates it" is enforced rather than hoped for.

And Money is doing three jobs no decimal could: it carries its currency, it refuses to add pounds to euros, and it works as a dictionary key with correct hashing you never wrote.


Common Mistakes

  1. Using a record where identity matters. Two users called Ada with the same age are not the same user. Records are for values, classes for entities.
  2. Expecting with to deep-copy. It copies references. A List<T> inside a record is shared with every copy you make.
  3. Assuming two records holding equal collections are equal. List<T> compares by reference, so they are not. Use ImmutableArray<T> plus a structural comparison, or override Equals.
  4. Writing record struct when you meant readonly record struct. The former's properties are mutable, which quietly defeats the point.
  5. Trying to validate positional parameters with a plain constructor. A positional record already has one; re-declare the property with a validating initialiser or use the body form instead.
  6. Making an EF Core entity a record. init-only properties fight change tracking, and value equality confuses identity resolution.
  7. Putting a mutable member in a record used as a dictionary key. The hash is computed from the fields; change one and the entry becomes unreachable — the same trap as last module, now easier to fall into.
  8. Reaching for record to avoid typing a class. If it has behaviour, dependencies and a lifecycle, the boilerplate you saved is not the boilerplate you needed.

Best Practices

  • Ask "are two of these with equal contents the same thing?" Yes → record. No → class. That one question settles nearly every case.
  • Prefer positional records for DTOs, messages and API contracts — one line, and the shape is self-documenting.
  • Use readonly record struct for small values like Money, Sku or Point: value semantics with no allocation.
  • Hold immutable collections inside records (ImmutableArray<T>, or at minimum IReadOnlyList<T>) so the shallow copy of with cannot surprise you.
  • Model state changes as new snapshots with with, and keep the history when the past has value — audit trails, undo, event sourcing.
  • Validate in a re-declared property initialiser or a body-form record, so an invalid record cannot be constructed at all.
  • Add behaviour freely. Computed properties, operators and an overridden ToString all belong on a record; immutable does not mean anaemic.
  • Let records be your dictionary and HashSet keys. Correct equality and hashing are generated, which is more than most hand-written keys manage.

Practice Exercises

  1. Define readonly record struct Sku(string Code, int Revision) and record Product(Sku Id, string Name, decimal Price). Create two Product values with identical contents, prove == is True while ReferenceEquals is False, then use Sku as a Dictionary key and look a product up with a freshly constructed key.
  2. Write record Booking(string Guest, DateOnly CheckIn, int Nights) with a computed CheckOut property. Produce three snapshots with with — extend the stay, change the guest, then both at once — and print all four, showing the original is untouched.
  3. Demonstrate the shallow-copy trap: build record Team(string Name, List<string> Members), copy it with with, add a member through the copy, and print both counts. Then fix it two ways — passing a new list in the with, and switching the field to IReadOnlyList<string> — and comment on which fix actually prevents the bug.
  4. Model a small event log: record Event(int Version, string Kind, string Detail) and a Ledger class holding IReadOnlyList<Event>, where Append returns a new Ledger rather than mutating. Add four events, print the log, then prove the original ledger still has zero events and explain in a comment what this buys you over a mutable List<Event>.