C# 14 and .NET 10 allow user-defined compound assignment operators that take the left operand by `ref`, so a large mutable struct can be updated in place instead of copied. The post shows a before/after `Vector` type and where the pattern bites.
Key points
- C# 14 in .NET 10 supports user-defined `+=` and `-=` operators on structs.
- The signature takes the left operand as `ref Vector`, so an update mutates the existing instance.
- The before sample uses a `readonly struct` with `operator +`, which yields a new value per call.
- The after sample drops `readonly` and declares `operator +=(ref Vector a, Vector b)`.
- Shared across threads, or callers expecting immutability, make `ref` operators the wrong tool.
- Verify the gain with BenchmarkDotNet instead of assuming the allocation disappears.
Why it matters
The useful part here is narrow but real: a compound assignment operator that receives `ref` removes the copy that `v = v + delta` implies for a big struct. Older language versions push you back to a mutating instance method, so on C# 14 keeping the arithmetic syntax costs you less.
Two caveats before rewriting a hot path. A stack local struct was never on the Gen0 heap to begin with, so measure the copy cost rather than imaginary allocations and confirm the win with BenchmarkDotNet. And the type stops being `readonly`; every place that shares it now needs a story for thread safety and for callers who expected immutability.
Real-world use
- Vector or matrix types in spatial and physics math where every operation currently returns a fresh instance.
- High-throughput domain logic that keeps large structs on the stack and wants to skip temporary copies.
- Hot loops that repeatedly add a small delta to a large value type.
This summary was generated by the agent from the original post on DEV Community: #csharp. The full text and all rights belong to its author and publisher. Go to original