skip to content

In C#, a level editor takes `CollectionsMarshal.AsSpan(placed)` on a `List<Placement>`, keeps adding entities, and some position writes through the span never appear; why, and what fixes it?

level: seniorimportance: nice to knowfreq 20%

answer

  1. a span over the current array
  2. growth replaces the backing array
  3. no version check on spans
  4. acquire after the last Add

basics

~20 s

The span covers the list's backing array as it was when AsSpan ran. An Add beyond Capacity moves the items to a new array, so later writes silently hit the old one. Take the span after the last Add or Remove.

solid answer

~50 s

`CollectionsMarshal.AsSpan(list)` returns a `Span<T>` over the first `Count` slots of the list's backing array: no copy, no link back to the list and no version check. Code uses it to update struct elements in place, since the `List<T>` indexer returns a copy. When a later `Add` exceeds `Capacity`, the list allocates a new array, copies the elements and drops the old one; the span still points at the old array, so writes through it never reach the list and nothing throws. Even without growth the span is stale: its `Length` does not include added items, and `Insert` or `RemoveAt` shift elements under fixed indexes. The method's own doc comment says items should not be added or removed while the span is in use. Do every structural change first, then call `AsSpan`, and re-acquire it after any `Add`, `Insert` or `Remove`.

code

csharp · 16 lines
csharp
using System.Runtime.InteropServices;

var placed = new List<Placement>(4) { new(1, 0, 0), new(2, 1, 0), new(3, 2, 0), new(4, 3, 0) };
Span<Placement> span = CollectionsMarshal.AsSpan(placed);
span[0].X = 10;                  // writes into the list's backing array
Console.WriteLine(placed[0].X);  // 10

placed.Add(new(5, 4, 0));        // Count 5 > Capacity 4: a new array, the old one abandoned
span[1].X = 99;                  // lands in the abandoned array
Console.WriteLine($"{placed[1].X} Capacity={placed.Capacity} span.Length={span.Length}");

span = CollectionsMarshal.AsSpan(placed); // re-acquire after every Add or Remove
span[1].X = 99;
Console.WriteLine($"{placed[1].X} span.Length={span.Length}");

record struct Placement(int Id, int X, int Y);

go deeper

for a junior

Know that CollectionsMarshal.AsSpan gives direct access to a List<T>'s elements and that items should not be added or removed while the span is in use.

for a middle

Explain that the span covers the backing array and Count at the moment of the call, and that growth replaces the array, so later writes miss the list.

for a senior

Diagnose silent lost updates as a stale span, explain why no exception appears, and restructure the code so structural changes finish before the span is taken or the span is re-acquired after each change.

for a principal

CollectionsMarshal trades safety for speed; agree when a team may use it, typically measured hot paths with a short, local span lifetime, and expect reviewers to check that nothing changes the list while the span lives.

## What `CollectionsMarshal.AsSpan` returns `System.Runtime.InteropServices.CollectionsMarshal` is described in its source as "an unsafe class that provides a set of methods to access the underlying data representations of collections". `AsSpan<T>(List<T>? list)` reads the list's private backing array and size and returns `new Span<T>(items, 0, size)`: a **view** over the elements currently in the list. Why reach for it at all? A `Span<T>` indexer returns a reference to the element, so `span[i].X = 10` changes the element where it lives. The `List<T>` indexer returns a copy of a struct element instead, which is why `placed[i].X = 10` does not compile on a list of structs; that copy rule is covered with struct and class semantics. A span also allocates nothing and avoids copying each struct out of the list and back, which is why editors and games use it for bulk updates. The cost is that the span knows nothing about the list. It holds a reference to **one array** and a **length**, both fixed at the moment `AsSpan` ran. The source's own comment on the method states the rule at its real strength: items **should not** be added or removed from the `List<T>` while the span is in use. Nothing enforces it. ## Why the writes vanish In the editor, the loader takes a span early, then keeps placing entities: 1. `AsSpan(placed)` returns a span over the current array, say 4 slots with 4 entities. 2. `placed.Add(...)` finds `Count == Capacity`, allocates an 8-slot array, copies the 4 entities into it and makes that the list's backing array. The 4-slot array is no longer referenced by the list. 3. `span[1].X = 99` writes into the **old** array, which only the span still references. 4. `placed[1].X` still reads the old value from the new array. No exception was thrown at any step. The snippet below prints `1 Capacity=8 span.Length=4` after the lost write, and `99 span.Length=5` once the span is re-acquired. ## What each list change does to a span you are holding | Change after `AsSpan` | Effect on the span | |---|---| | `Add` that fits in `Capacity` | same array, but `Length` is old, so the new item is not visible | | `Add` or `Insert` that grows | span points at the abandoned array; writes are lost | | `Insert` or `RemoveAt` without growth | elements shift, so `span[i]` now refers to a different entity; for plain structs the slot past the new `Count` keeps its old value | | `Clear` | slots are cleared only when `T` holds references; a span over plain structs keeps reading old data | | `Sort`, `Reverse`, an index assignment | elements change where they are, and the span sees the new contents | A `ref` local taken from the span (`ref Placement p = ref span[0];`) has the same problem: after growth it refers into the old array. ## Why nothing throws `List<T>` detects modification only through its **version** field, which every structural change increments and which the list's `Enumerator` checks on each `MoveNext`, throwing `InvalidOperationException` when a `foreach` sees the list change underneath it. A span is not an enumerator of the list; it is a pointer and a length with no access to the version. Lost writes therefore surface only as wrong data, often far from the line that caused them. ## Fixes - **Finish structural changes first.** Load and add every entity, then call `AsSpan` and run the update loop. - **Re-acquire after every `Add`, `Insert` or `Remove`.** Treat the span as valid only until the next structural change, and keep it in a local inside the loop that uses it. The compiler already stops you from storing it in a class field: **CS8345**, because `Span<T>` is a ref struct. - **`EnsureCapacity` is not enough on its own.** Reserving room prevents the reallocation, but the span's `Length` still excludes items added later, and inserts and removals still shift elements. - **Use the indexer when performance does not matter**: `placed[i] = placed[i] with { X = 99 };` writes a whole new value through the list and can never be stale. - **`CollectionsMarshal.SetCount`** is the related tool for pre-sizing before filling through a span; it changes `Count` and exposes the slots as they are, possibly uninitialized, so the same discipline applies.

  • Why doesn't the list throw `InvalidOperationException` here as it does when you add during a `foreach`?
    That exception comes from `List<T>.Enumerator`, which records the list's version when the loop starts and compares it on every `MoveNext`. `CollectionsMarshal.AsSpan` returns a plain `Span<T>` over the backing array, with no reference to the list and no version to check, so a structural change cannot be detected and the result is silent data loss instead.
  • If you call `EnsureCapacity(finalCount)` before taking the span, is it safe to keep adding?
    It is safer but not safe. With enough capacity no reallocation happens, so writes to existing slots still reach the list. But the span's `Length` was fixed when `AsSpan` ran, so new items are outside it, and any `Insert` or `RemoveAt` shifts elements under your indexes. Re-acquire the span after the additions.

  • The span from CollectionsMarshal.AsSpan follows the list when it grows.
  • Adding while holding the span throws InvalidOperationException, so the bug cannot go unnoticed.
  • Calling EnsureCapacity first makes one span valid for the whole load.
  • AsSpan copies the list, so writes through it never touch the list.
  • Storing the span in a field keeps it current.