Language: C# · Versions: C# 13 / .NET 9.0
The problem
I'm taking a Span<int> over a List<int> using CollectionsMarshal.AsSpan(list) to update an element in-place with the result of a helper function. However, the helper function appends a diagnostic entry to the same List<int>, causing the list's internal _items array to reallocate. The write through the original span reference silently writes into the abandoned old array instead of the resized List<int>.
Minimal example
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
var list = new List<int>(capacity: 2) { 10, 20 };
ref int slot = ref CollectionsMarshal.AsSpan(list)[0];
slot += ComputeAndLog(list, 5);
Console.WriteLine(string.Join(", ", list));
static int ComputeAndLog(List<int> log, int delta)
{
log.Add(999); // Triggers capacity growth from 2 -> 4, reallocating _items!
return delta;
}
Expected
list should contain 15, 20, 999.
What happens instead
list prints 10, 20, 999 because ref int slot was bound to &oldArray[0] before ComputeAndLog ran, and log.Add(999) allocated a new backing array before slot += 5 wrote 15 to the old array.
In performance-critical C# 13 code that uses CollectionsMarshal.AsSpan, what are the best compile-time or architectural ways to prevent span/ref invalidation across call boundaries without copying the list?
Your diagnosis is right, and this isn't new to C# 13. A ref local has worked this way since C# 7. Here is a fix that keeps the zero-copy write:
// 1. Do everything that can grow the list first, then take the ref.
int delta = ComputeAndLog(list, 5);
CollectionsMarshal.AsSpan(list)[0] += delta; // 15, 20, 999
Why the write is lost
ref int slot = ref CollectionsMarshal.AsSpan(list)[0]; points at element 0 of whatever _items array exists at that moment. The C# spec defines x op= y as x = x op y, with x evaluated only once. So the steps are:
- Read 10 from the old array.
- Call
ComputeAndLog.Addcopies the old array, still holding 10, into a new array of 4. - Write 15 into the old array.
The GC keeps the old array alive because your ref still points at it. That's why nothing crashes and the write simply disappears. Plain list[0] += ComputeAndLog(list, 5) would print 15. That line calls the indexer's setter after the right-hand side runs, so the setter finds the current _items. I reasoned this from the spec; I haven't run it. The CollectionsMarshal.AsSpan docs state the rule: don't add or remove items while the span is in use.
No compile-time guard exists
Ref-safety rules like scoped and ref escape only stop a ref from outliving its stack frame. They don't check whether the list behind it gets reallocated. I don't know of any built-in Roslyn analyzer for this either. What you can do:
- Make the callee unable to grow the list. If the helper takes a
Span<int>orReadOnlySpan<int>instead ofList<int>, it can't callAdd, and the type system enforces that. Send diagnostics to a separate sink, not the data list. - Order the work. Run every call that might grow the list first, and only then take the span. Treat the span as valid only until the next call that could mutate the list.
- Reserve capacity up front. Call
list.EnsureCapacity(list.Count + maxAppends)(available since .NET 6) before taking the span. ThenAddwon't reallocate and the ref stays valid. This breaks as soon as the append count is wrong. - Own the buffer. In hot code, keep a
T[]plus a count yourself, or rent one fromArrayPool<T>. Then you decide exactly when the buffer grows and can bump a version number when it does. - Catch it in debug builds:
int cap = list.Capacity;
slot += ComputeAndLog(list, 5);
Debug.Assert(list.Capacity == cap, "list reallocated under a live span");
The assert misses one case: a Clear followed by TrimExcess that lands on the same capacity. Mutation through a span isn't checked against List<T>._version, so nothing at runtime will catch this for you. If you need a compile-time check, you'd have to write a custom analyzer that flags any call taking the list while a ref from AsSpan is still live.