Skip to content

Structs and Value Semantics

The Course
•
25 min study

This course ends with a concurrent job runner, and it spends the week on what that takes: precise types, asynchronous code, channels and careful use of memory. It assumes you've done the Intermediate course, or that you're comfortable with interfaces, generics, LINQ and Result-style error handling.

One thing to keep in mind all week: this browser runtime has a single thread. Asynchronous code works as it does anywhere, but several things that run at the same time on your computer take turns here. Lessons point out each place where that matters.

Copies, not references

A class variable holds a reference, so two variables can share one object. A struct variable holds the value itself, and assignment copies it. int, double and DateOnly are all structs. Predict both lines.

Shared or copied? C#
var classA = new PointClass { X = 1 };
var classB = classA;
classB.X = 99;
Console.WriteLine(classA.X);

var structA = new PointStruct { X = 1 };
var structB = structA;
structB.X = 99;
Console.WriteLine(structA.X);

class PointClass
{
    public int X { get; set; }
}

struct PointStruct
{
    public int X { get; set; }
}
Check your prediction
Text
99
1

The mutable struct trap

Reading a struct from a list gives you a copy. Changing the copy doesn't change the list, and the compiler rejects the direct form with an error, since it would be silently useless. Calling a mutating method on it is allowed, and it really is silently useless.

The change that vanished C#
var counters = new List<Counter> { new Counter() };

counters[0].Increment();
Console.WriteLine(counters[0].Value);

Counter copy = counters[0];
copy.Increment();
counters[0] = copy;
Console.WriteLine(counters[0].Value);

struct Counter
{
    public int Value { get; private set; }

    public void Increment()
    {
        Value++;
    }
}
Check your prediction
Text
0
1

That's why the standard advice is to make a struct readonly. Every "change" then has to produce a new value, and this bug can't happen. The compiler checks that nothing in the struct is reassigned.

A readonly struct C#
var start = new Point(1, 2);
Point moved = start.Move(10, 0);

Console.WriteLine(start);
Console.WriteLine(moved);

readonly struct Point(int x, int y)
{
    public int X { get; } = x;
    public int Y { get; } = y;

    public Point Move(int dx, int dy) => new Point(X + dx, Y + dy);

    public override string ToString() => $"({X}, {Y})";
}
Check your prediction
Text
(1, 2)
(11, 2)

default skips your constructor

A struct always has a default value in which every field is zero or null. default(T), the contents of a new array, and an unset field all produce it without running any constructor. So validation in a struct's constructor can be bypassed, and methods need to handle the all-zero value.

Bypassing validation C#
var valid = new Percent(50);
Percent unset = default;
Percent[] array = new Percent[1];

Console.WriteLine(valid.Value);
Console.WriteLine(unset.Value);
Console.WriteLine(array[0].Value);

try
{
    new Percent(101);
}
catch (ArgumentOutOfRangeException)
{
    Console.WriteLine("refused");
}

readonly struct Percent
{
    public int Value { get; }

    public Percent(int value)
    {
        ArgumentOutOfRangeException.ThrowIfGreaterThan(value, 100);
        ArgumentOutOfRangeException.ThrowIfNegative(value);
        Value = value;
    }
}
Check your prediction
Text
50
0
0
refused

Zero is fine for Percent. If it isn't a sensible value for your type, a class may be the better choice.

Boxing

Storing a struct in an object or an interface variable wraps it in a new heap object, called boxing. That costs an allocation, and the box holds a separate copy. Generics avoid it: a List<int> stores real int values, and List<object> would box each one.

The box is a copy C#
int number = 1;
object boxed = number;
number = 2;

Console.WriteLine(boxed);
Console.WriteLine(number);
Console.WriteLine(ReferenceEquals(boxed, boxed));

object first = 5;
object second = 5;
Console.WriteLine(ReferenceEquals(first, second));
Console.WriteLine(first.Equals(second));
Check your prediction
Text
1
2
True
False
True

Choosing

Prefer a struct whenPrefer a class when
It represents one small value, such as a coordinateIt has an identity that outlives its values
It's roughly 16 bytes or less, and immutableIt's large, because each copy costs that size
All-zero is a sensible valueIt must always pass validation

A struct isn't automatically faster. Large ones are slower because of copying, and casts to interfaces box them. Measure before deciding that performance is the reason.

Your turn

Exercise

A distance value

Write a readonly struct Distance holding Meters as a double, with a static factory method FromKm(double km), a Plus(Distance other) method that returns a new value, and a ToString that prints 1500 m. A negative distance must throw ArgumentOutOfRangeException.

Print 1.5 km, the result of adding 500 m to it, the original again, and the value of default(Distance). Then show that FromKm(-1) is refused.

When it works, it prints:

Text
1500 m
2000 m
1500 m
0 m
refused
Your workspace C#
Console.WriteLine("Start here");
Hint 1: the idea

Every operation creates a new Distance, so the constructor is the single place that validates. Make the factory and Plus go through it.

Hint 2: a first step

Start with the constructor and ToString. Remember that default gives 0 without running your code, and that's fine for a distance.

Show one solution
C#
Distance walk = Distance.FromKm(1.5);
Console.WriteLine(walk);
Console.WriteLine(walk.Plus(new Distance(500)));
Console.WriteLine(walk);
Console.WriteLine(default(Distance));

try
{
    Distance.FromKm(-1);
}
catch (ArgumentOutOfRangeException)
{
    Console.WriteLine("refused");
}

readonly struct Distance
{
    public double Meters { get; }

    public Distance(double meters)
    {
        ArgumentOutOfRangeException.ThrowIfNegative(meters);
        Meters = meters;
    }

    public static Distance FromKm(double km) => new Distance(km * 1000);

    public Distance Plus(Distance other) => new Distance(Meters + other.Meters);

    public override string ToString() => $"{Meters} m";
}
Text
1500 m
2000 m
1500 m
0 m
refused

Was this article helpful?

Your response is saved on this device.