Skip to content

Record Structs and Object Initialization

The Course
•
25 min study

The last lesson's Edge took a dozen lines of equality code. A readonly record struct generates all of it. Today's lesson also covers the tools for making an object correct from the moment it exists.

readonly record struct

This one line provides properties, a constructor, value equality, a matching hash code, a ToString, ==, != and with. The generated equality avoids the slow default used by plain structs. readonly matters: a plain record struct has properties that can be set.

One line of declaration C#
var a = new Point(1, 2);
var b = a with { Y = 9 };

Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(a == new Point(1, 2));
Console.WriteLine(new HashSet<Point> { a, new Point(1, 2), b }.Count);

var loose = new LoosePoint(1, 2);
loose.X = 5;
Console.WriteLine(loose);

readonly record struct Point(int X, int Y);

record struct LoosePoint(int X, int Y);
Check your prediction
Text
Point { X = 1, Y = 2 }
Point { X = 1, Y = 9 }
True
2
LoosePoint { X = 5, Y = 2 }

Validating a record

A positional record's generated constructor just stores its values. To enforce a rule, redeclare the property and validate in its initializer. There's a catch, though. with copies the value and then runs the init accessor of the property you set, not the initializer, so a rule in the initializer can be bypassed. An init accessor is the sturdy place for it.

with bypasses the initializer C#
var weak = new WeakAge(30);
Console.WriteLine((weak with { Years = -5 }).Years);

var strong = new StrongAge(30);
try
{
    _ = strong with { Years = -5 };
}
catch (ArgumentOutOfRangeException)
{
    Console.WriteLine("refused by with");
}

try
{
    new StrongAge(-5);
}
catch (ArgumentOutOfRangeException)
{
    Console.WriteLine("refused by constructor");
}

record WeakAge(int Years)
{
    public int Years { get; init; } = Years >= 0 ? Years : throw new ArgumentOutOfRangeException(nameof(Years));
}

record StrongAge
{
    public StrongAge(int years)
    {
        Years = years;
    }

    public int Years
    {
        get => field;
        init
        {
            ArgumentOutOfRangeException.ThrowIfNegative(value);
            field = value;
        }
    }
}
Check your prediction
Text
-5
refused by with
refused by constructor

required and init

init allows a value to be set during object creation only. required makes the compiler insist on it at every creation site. Together, they give a readable alternative to a long constructor, particularly for options, as with the job runner's RunnerOptions. The compiler's error names exactly what's missing.

The compiler checks the initializer C#
var ok = new Settings { Name = "main" };
Console.WriteLine(ok);

var missing = new Settings { Retries = 5 };

record Settings
{
    public required string Name { get; init; }
    public int Retries { get; init; } = 3;
}
Check your prediction
Text
error CS9035
Name

Remove the missing line, and this prints the settings with a default of 3 retries. required is checked at compile time only, so a deserializer that's unaware of it could still leave a field unset. System.Text.Json does respect it.

Immutable collections inside

init and readonly protect a field, not the object inside it. readonly List<int> still lets anyone add to the list. For state that's shared, particularly across asynchronous operations, an immutable collection makes it impossible to change by accident. Each "change" returns a new collection, and shares memory with the old one.

readonly doesn't mean deeply immutable C#
using System.Collections.Immutable;

var box = new Box(new List<int> { 1 });
box.Items.Add(2);
Console.WriteLine(box.Items.Count);

ImmutableList<int> first = ImmutableList.Create(1);
ImmutableList<int> second = first.Add(2);
Console.WriteLine(first.Count);
Console.WriteLine(second.Count);

record Box(List<int> Items);
Check your prediction
Text
2
1
2

Your turn

Exercise

A date range

Write a readonly record struct DateRange with Start and End as DateOnly, where the range includes both. Creating one with End before Start must throw ArgumentException. Add Days (the count, so a single day is 1), Contains(DateOnly date), and Overlaps(DateRange other).

Using 2026-01-10 to 2026-01-20, print Days, whether it contains 2026-01-20 and 2026-01-21, whether it overlaps a range starting on 2026-01-20, and whether it overlaps one starting on 2026-01-21. Then show that a reversed range is refused.

When it works, it prints:

Text
11
True
False
True
False
refused
Your workspace C#
var start = new DateOnly(2026, 1, 10);
Console.WriteLine(start.DayNumber);
Hint 1: the idea

Two ranges overlap unless one ends before the other begins. It's easier to state that negative and then flip it.

Hint 2: a first step

A positional declaration stores values without any validation, so write an explicit constructor that checks its arguments, and get-only properties it sets, so a check can't be skipped later with with. DayNumber gives the arithmetic for Days.

Show one solution
C#
var range = new DateRange(new DateOnly(2026, 1, 10), new DateOnly(2026, 1, 20));

Console.WriteLine(range.Days);
Console.WriteLine(range.Contains(new DateOnly(2026, 1, 20)));
Console.WriteLine(range.Contains(new DateOnly(2026, 1, 21)));
Console.WriteLine(range.Overlaps(new DateRange(new DateOnly(2026, 1, 20), new DateOnly(2026, 2, 1))));
Console.WriteLine(range.Overlaps(new DateRange(new DateOnly(2026, 1, 21), new DateOnly(2026, 2, 1))));

try
{
    new DateRange(new DateOnly(2026, 2, 1), new DateOnly(2026, 1, 1));
}
catch (ArgumentException)
{
    Console.WriteLine("refused");
}

readonly record struct DateRange
{
    public DateOnly Start { get; }
    public DateOnly End { get; }

    public DateRange(DateOnly start, DateOnly end)
    {
        if (end < start)
        {
            throw new ArgumentException("end is before start");
        }
        Start = start;
        End = end;
    }

    public int Days => End.DayNumber - Start.DayNumber + 1;

    public bool Contains(DateOnly date) => date >= Start && date <= End;

    public bool Overlaps(DateRange other) => !(other.End < Start || other.Start > End);
}
Text
11
True
False
True
False
refused

Remember the catch from the first lesson: default(DateRange) still exists and has a zero Start and End. That happens to be a valid one-day range here.

Was this article helpful?

Your response is saved on this device.