DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

Rebuilding collection expressions and spreads

Collection expressions look like one feature — square brackets that build a collection — but there is no "collection expression" opcode, and more surprisingly, no single lowering. [1, 2, 3] compiled against an int[] and [1, 2, 3] compiled against a List<int> produce IL that shares not one instruction. The brackets are a request; the target type chooses how it is filled. For anyone reading compiled code, that makes a collection expression a moving target: you cannot recognize it by a signature, only by knowing the handful of shapes it can take.

The real question

The compiler picks a construction strategy per target type, and then erases every trace of the brackets. So Glass is not decoding an instruction — it is asking, for a given span of IL, which strategy produced this, and does it reconstitute a collection expression. That means matching one of a small set of templates — an array initializer, an empty-array call, a List<T> fill, a stack-buffer span, a [CollectionBuilder] factory — and, when a spread is involved, recognizing a copy that moves a whole source into place. The reasoning runs from the target type outward, not from any opcode.

Five targets, five lowerings

Start with the same literal elements aimed at different types.

An array. int[] x = [1, 2, 3]; lowers exactly like an array initializer. For three blittable constants the compiler blob-serializes them into a read-only data field and copies the blob in one call:

ldc.i4.3
newarr     [System.Runtime]System.Int32
dup
ldtoken    field valuetype '<PrivateImplementationDetails>'/'__StaticArrayInitTypeSize=12'
           '<PrivateImplementationDetails>'::'2D7...F4'
call       void [System.Runtime]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(
             class [System.Runtime]System.Array, valuetype [System.Runtime]System.RuntimeFieldHandle)
Enter fullscreen mode Exit fullscreen mode

The element count survives only as TypeSize=12 (12 bytes / sizeof(int) = 3). There is no bracket, and nothing distinguishes this from new int[] { 1, 2, 3 } — because the language defines them to be the same.

An empty array. int[] x = []; is not an allocation at all:

call       !!0[] [System.Runtime]System.Array::Empty<int32>()
Enter fullscreen mode Exit fullscreen mode

One call, byte-identical to Array.Empty<int>().

A List<T>. List<int> x = [1, 2, 3]; constructs the list with a known capacity and writes the elements in. The length is known, so there are no reallocations:

ldc.i4.3
newobj     instance void class [System.Collections]System.Collections.Generic.List`1<int32>::.ctor(int32)
dup
ldc.i4.1
callvirt   instance void class ...List`1<int32>::Add(!0)
// … Add(2), Add(3) …
Enter fullscreen mode Exit fullscreen mode

A span. ReadOnlySpan<int> s = [1, 2, 3]; with constants rides the same read-only blob as the array, but via RuntimeHelpers.CreateSpan, which hands back a span pointing at the data field with zero allocation. When the elements are variables, there is nothing constant to park, so the compiler stack-allocates an [InlineArray(3)] scratch buffer — a synthetic <>y__InlineArray3 struct — fills three slots, and takes a span over it. (That inline-array machinery is the same one covered in the custom-collection-builder post.)

An ImmutableArray<T>. ImmutableArray<int> x = [1, 2, 3]; goes through yet another door: ImmutableArray<T> carries [CollectionBuilder(typeof(ImmutableArray), "Create")], so the brackets lower to a span plus call ImmutableArray::Create<int32>(ReadOnlySpan<int32>) — no constructor, no Add. Folding that back is the builder problem, covered in the post linked above.

Five targets, five unrelated instruction sequences, one source syntax. This is why a decompiler cannot have a "collection-expression detector": it needs one recognizer per strategy, each keyed to the target type.

The spread operator

The spread .. is where it gets mechanical. [..a, ..b] means concatenate the elements of a and b, and the compiler lowers it according to whether each source's length is known in advance.

When the sources are countable (arrays, spans, anything with Count/Length), the result length is a sum computed up front, the result is allocated once, and each source is bulk-copied into a contiguous sub-slice:

int[] r = [..a, ..b];           // a, b are int[]
Enter fullscreen mode Exit fullscreen mode

lowers, in effect, to:

int[] r = new int[a.Length + b.Length];
Span<int> dst = r;
int i = 0;
((ReadOnlySpan<int>)a).CopyTo(dst.Slice(i, a.Length));  i += a.Length;
((ReadOnlySpan<int>)b).CopyTo(dst.Slice(i, b.Length));
Enter fullscreen mode Exit fullscreen mode

No per-element loop at all — just two CopyTo calls into a pre-sized buffer. For a List<int> target the same known-length copy uses CollectionsMarshal: set the count, take a span over the list's backing store, and CopyTo into it:

List<int> r = [..a, ..b];
Enter fullscreen mode Exit fullscreen mode

becomes:

var r = new List<int>();
CollectionsMarshal.SetCount(r, a.Length + b.Length);
Span<int> dst = CollectionsMarshal.AsSpan(r);
int i = 0;
((ReadOnlySpan<int>)a).CopyTo(dst.Slice(i, a.Length));  i += a.Length;
((ReadOnlySpan<int>)b).CopyTo(dst.Slice(i, b.Length));
Enter fullscreen mode Exit fullscreen mode

When a spread source is not countable — a bare IEnumerable<T> whose length cannot be known — bulk copy is impossible, and the compiler falls back to the thing people picture when they hear "spread": a foreach that adds each element:

List<int> r = [first, ..items];   // items is IEnumerable<int>
Enter fullscreen mode Exit fullscreen mode

lowers to:

var r = new List<int>();
r.Add(first);
foreach (int item in items)
    r.Add(item);
Enter fullscreen mode Exit fullscreen mode

So a single [..x, ..y] can be two CopyTo calls or a foreach/Add loop, depending entirely on what x and y are. Both are the same syntax; the IL is unrecognizable between them.

A collection expression borrows its target type's construction strategy and erases the brackets. Glass keys recovery on the target type and the copy shape, not on any single opcode.

How Glass folds it back

Glass carries one recognizer per strategy and runs them against the target type it already knows from metadata.

  1. Array. A newarr immediately followed by InitializeArray over a <PrivateImplementationDetails> field (constants), or by a run of stelem at ascending constant indices (non-constants), is the array form. A lone Array::Empty<T>() is [].
  2. List<T>. A List constructor followed by a run of Add calls, or by CollectionsMarshal.SetCount + AsSpan + copies, is the list form; the capacity argument and the SetCount value both equal the recovered element count.
  3. Span. A CreateSpan over a data field, or an initobj of a <>y__InlineArrayN local followed by slot writes and InlineArrayAsReadOnlySpan, yields the elements directly.
  4. Spread. For each source, Glass looks for the whole source moving into a contiguous destination sub-slice at the running offset — a CopyTo into dst.Slice(i, source.Length), or a foreach over the source whose body is a single Add. That whole-source-into-place shape is what it rewrites as ..source. A loose element, written singly, stays a plain element.

Only when a region matches one template end to end does Glass print [ … ] with the spreads it recovered. Otherwise it prints the literal array, list, or copy calls — because that is what the code is.

When it can't decide

The honest limit is the same one every "sugar over ordinary code" feature has: the sugar and the hand-written form are byte-identical, so no metadata can separate them.

  • int[] x = [1, 2, 3]; and int[] x = new int[] { 1, 2, 3 }; compile to the same newarr/InitializeArray. Glass renders one spelling; both recompile to the same assembly.
  • int[] x = []; and Array.Empty<int>() are one call. Indistinguishable.
  • A spread foreach/Add loop and a hand-written foreach (var i in items) r.Add(i) are the same IL. Glass folds to ..items only when the loop is the compiler's exact pattern — a bare Add body over the whole source, feeding a collection built in the same expression — and prints the literal loop the moment the body does anything else.

In every ambiguous case Glass chooses the reading that round-trips and is honest about the tie: it never invents a spread from a loop that merely resembles one.

Using this when you read code

When Glass shows you [..a, ..b], read the two CopyTo calls (or the copy loop) as recovered, not transcribed — they round-trip, but the compiler, not the author, chose CollectionsMarshal or CreateSpan. When you see a bare [1, 2, 3] on a ReadOnlySpan<int> local, that is your cue that there is a stack scratch buffer or an RVA data field one hop away — jump to it in the IL view to see the real bytes. And when Glass leaves an explicit CopyTo or Add loop instead of brackets, that is it telling you it could not prove the code was a collection expression, and you should read the instructions literally.

Takeaway

A collection expression has no opcode and no single lowering: the target type picks InitializeArray, Array.Empty, a List fill, a span scratch buffer, or a [CollectionBuilder] factory, and a spread becomes a bulk CopyTo or a copy loop depending on whether its source has a known length. Glass recovers the brackets by matching those templates against the target type it reads from metadata — and falls back to the literal construction the instant the shape is not exact. Knowing that the brackets are a recognized strategy, not a recorded keystroke, is what lets you trust the recovered syntax and spot when the expanded form in front of you is the real code.

Glass.NET is a free .NET decompiler with a VS-native Avalonia UI, a headless CLI, and an MCP server. It reads metadata and IL statically and never executes the assembly you open — point it at your own binaries or at third-party dependencies you are auditing or debugging. Grab it at /products/glass.

Top comments (0)