Production Context
When writing high-throughput domain logic in C#, heavy use of immutable value types or custom mathematical structs can quickly pollute the Gen0 heap if not handled carefully. Historically, writing vector = vector + delta; meant the runtime allocated a temporary instance of the struct, even when working entirely on the stack.
C# 14 and .NET 10 introduce direct support for overloading custom compound assignment operators (+=, -=) using ref parameters. This lets us update large value types in-place without triggering defensive copying or hidden temporary allocations.
Before
public readonly struct Vector(double x, double y)
{
public double X { get; } = x;
public double Y { get; } = y;
public static Vector operator +(Vector a, Vector b)
=> new(a.X + b.X, a.Y + b.Y);
}
// Usage triggers an intermediate struct instantiation
Vector v = new(1.0, 2.0);
v = v + new(3.0, 4.0);
After
public struct Vector(double x, double y)
{
public double X = x;
public double Y = y;
public static void operator +=(ref Vector a, Vector b)
{
a.X += b.X;
a.Y += b.Y;
}
}
// Usage mutates the stack frame directly with zero overhead
Vector v = new(1.0, 2.0);
v += new(3.0, 4.0);
Why it matters
- Zero Allocations: Eliminates intermediate struct instantiation during tight mathematical or spatial calculations.
- Direct Stack Mutation: Operates on references directly, keeping CPU cache lines hot.
- Cleaner Syntax: Maintains readable arithmetic syntax while delivering low-level span-like performance.
Watch out
Be mindful when applying ref to struct operators if your types are shared across multiple threads or expected to behave immutably. Always verify your hot paths using BenchmarkDotNet to confirm the allocation drop.
Have you profiled struct allocation hot paths in your domain models lately?

Top comments (1)
0 B intermediate struct allocations is a small number with a big consequence — the old
vector = vector + deltapattern silently paid for a throwaway instance on every single addition, and in a tight spatial loop that is exactly the kind of cost that never shows up in a profiler as one big block. Therefoverload on+=keeping the mutation in place with cache lines hot is the part I'd want to benchmark. Have you measured this on a real hot path — say a physics step or a mesh transform loop — and if so, how much of the Gen0 pressure actually disappeared versus just moving?