Custom Compound Assignment Operators in C# 14 / .NET 10

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?