How ref fields in a ref struct decompile
Decompile a modern ref struct and you can hit a field whose type is int32& — a field that holds a reference, not a value. Before C# 11 that was impossible: the runtime flatly rejected a byref-typed field, and the one type that needed one, Span<T>, smuggled it in through an internal intrinsic. C# 11 made ref fields a first-class language feature, and now Span<T> is built on one in plain sight. A decompiler that was written before this existed tends to choke on the field — showing an opaque pointer, or the old wrapper type, or nothing at all. Reconstructing it correctly means reading three things the metadata keeps: the byref field signature, the difference between rebinding the field and writing through it, and the scoped / [UnscopedRef] annotations that govern its lifetime. This post walks all three and shows what Glass recovers.
The real question
A ref field is just a field whose type is a managed reference, ref T. The source rule around it is small — a ref field may only appear inside a ref struct — but the consequences are not, because now the same syntax can mean two different things. _value = x and _value = ref x are both assignments to the field, but one writes a value through the reference and the other replaces the reference. The metadata keeps the distinction, but it keeps it in the choice of IL instruction, not in the field. So the question a decompiler must answer is: given a field typed int32& and a handful of ldfld/stfld/stind instructions around it, which assignments were ref-reassignments and which were writes through — and what were this field's lifetime annotations?
The field itself
Start with a minimal ref struct that wraps a reference to an int:
public ref struct IntRef
{
private ref int _value;
public IntRef(ref int value) => _value = ref value;
public int Value
{
get => _value; // read through the ref
set => _value = value; // write through the ref
}
public void Rebind(ref int other) => _value = ref other; // replace the ref
}
The field compiles to an ordinary field definition with an extraordinary signature:
.field private int32& _value
That trailing & is the whole story. In the FieldSig blob the type is ELEMENT_TYPE_BYREF (0x10) wrapping ELEMENT_TYPE_I4 (0x08), so the three bytes are 06 10 08 — FIELD, BYREF, I4. The runtime only accepts that signature on a type marked IsByRefLike (a ref struct); put it on a class or an ordinary struct and the type fails to load. That constraint is the reason the field and the ref struct requirement are inseparable, and it is the first thing Glass checks when it sees a byref field — the enclosing type is always a ref struct, and it renders it as one.
Rebind versus write-through
Here is where a value field and a ref field diverge sharply. Look at the constructor and Rebind — both perform _value = ref …:
.method public hidebysig specialname rtspecialname instance void .ctor(int32& value) cil managed
{
ldarg.0 // this (a managed pointer to the ref struct)
ldarg.1 // the incoming int32& 'value'
stfld int32& IntRef::_value // store the reference INTO the field
ret
}
stfld into a byref-typed field stores a reference. After it runs, _value points at whatever value pointed at. Rebind is byte-for-byte the same shape with other in place of value. Now the property that writes through the field:
.method public hidebysig specialname instance void set_Value(int32 'value') cil managed
{
ldarg.0
ldfld int32& IntRef::_value // load the reference held in the field
ldarg.1 // the int to store
stind.i4 // store it AT that address
ret
}
Completely different. set_Value first reads the field with ldfld to get the reference it holds, then dereferences it with stind.i4 to write the value where it points — the field is untouched. The getter mirrors it: ldarg.0; ldfld int32& IntRef::_value; ldind.i4. So the signal is exact. A stfld into a byref field is a ref-reassignment (= ref); a ldfld of that field followed by stind/stobj is a write through it (plain =). Glass distinguishes them on precisely that pattern, which is why it can put the ref back in _value = ref other and leave it out of _value = value.
scoped and [UnscopedRef]
Ref fields make references escape in ways the compiler has to police — a ref struct holding a ref int could outlive the local it points at. C# 11 enforces this with ref-safety analysis, and two keywords tune it: scoped narrows a reference's lifetime (it may not escape the method), and [UnscopedRef] widens it (a ref return may reach into this). Both are pure compile-time rules, so they survive compilation only as attributes.
A scoped parameter gets ScopedRefAttribute welded onto its parameter row:
static int Sum(scoped ReadOnlySpan<int> xs) { /* ... */ }
.param [1]
.custom instance void System.Runtime.CompilerServices.ScopedRefAttribute::.ctor() = ( 01 00 00 00 )
A member marked [UnscopedRef] — common on a struct method that returns ref to one of its own fields — gets the mirror-image attribute:
[UnscopedRef] public ref int AsRef() => ref _value;
.custom instance void System.Runtime.CompilerServices.UnscopedRefAttribute::.ctor() = ( 01 00 00 00 )
ScopedRefAttribute is compiler-reserved — you are not meant to write it by hand, and when the target framework lacks the type the compiler embeds a private copy (marked Microsoft.CodeAnalysis.EmbeddedAttribute), exactly as it does for the nullable and IsReadOnly attributes. UnscopedRefAttribute, by contrast, is a public type in System.Runtime.CompilerServices that you do write as [UnscopedRef]. There is a third marker that gives the first two their meaning: the module carries [RefSafetyRules(11)], stamped once per assembly, declaring that it was compiled under C# 11 ref-safety. Glass reads it to know the lifetime attributes are live, reconstructs scoped from ScopedRefAttribute, writes [UnscopedRef] from its attribute, and — like any compiler-embedded plumbing — does not surface the embedded ScopedRefAttribute type itself as source you wrote.
The pre-C#11 contrast: ByReference<T>
None of this existed before .NET 7, yet Span<T> has always needed a reference inside a value type. The runtime solved it with an internal intrinsic struct, System.ByReference<T>, that wrapped a managed pointer and was handled specially by the JIT. Old Span<T> was, in effect:
// pre-.NET 7
public readonly ref struct Span<T>
{
private readonly ByReference<T> _pointer;
private readonly int _length;
}
Decompile a Span from that era and the ByReference<T> wrapper is genuinely what the field was — that is honest output. From .NET 7 / C# 11 onward the wrapper is gone and Span<T> holds a real ref field:
// .NET 7+
public readonly ref struct Span<T>
{
internal readonly ref T _reference;
private readonly int _length;
}
So "what does a reference inside a ref struct look like" has two correct answers depending on the runtime, and Glass shows whichever the assembly actually uses — the intrinsic for the old shape, the ref T field for the new one. A readonly ref field (a ref you can rebind only in the constructor) and a ref readonly field (a reference to read-only storage) are both expressible too, and Glass distinguishes them from the field's initonly flag and the modreq(InAttribute) on the referent respectively.
How to use it
Point Glass at the assembly and read the type. The byref field comes back as a ref field, the rebinds as = ref, and the lifetime keywords in place:
glass decompile Buffers.dll --type IntRef
glass decompile Buffers.dll --type IntRef --il # see stfld vs ldfld+stind
The IL view is where the mechanism is legible: the .field … int32& line is the byref field, and the stfld/ldfld instructions around it are what Glass reads to decide which assignments were ref-reassignments. Seeing them beside the recovered C# is the quickest way to trust that a = ref really was a rebind and not a write-through. Exporting the type to a buildable project emits the ref field, the ref struct modifier the field requires, and the scoped / [UnscopedRef] annotations, so the round-tripped source compiles under the same ref-safety rules.
When it breaks
The recovery leans on the field's byref signature and the ordinary stfld/ldfld idioms around it. Hand-written or obfuscated IL can store into a byref field through less conventional paths, and if the field is read into a temporary that is then reused, the ldfld-then-stind write-through chain can be obscured — in which case Glass falls back to showing the reference and the indirect store as they are rather than inventing a clean = ref. The lifetime annotations are only as trustworthy as the attributes: strip ScopedRefAttribute and the scoped keyword is unrecoverable, because nothing else records it. That is the honest limit — the IL still describes the memory operations exactly; it is the source-level intent that thins out.
Takeaway
A ref field is a field whose signature carries ELEMENT_TYPE_BYREF, legal only inside a ref struct, and the feature that finally let Span<T> drop its ByReference<T> intrinsic. Recovering it means reading the & in the field signature, separating a stfld-into-byref rebind from a ldfld-then-stind write-through, and reconstructing scoped and [UnscopedRef] from the attributes that are their only trace. Glass does all of it, so a modern ref struct reads back as the ref fields and lifetime annotations you wrote, not as an opaque pointer. Glass is a free .NET decompiler; see Glass and the docs.
Comments
Join the discussionNo comments yet. Be the first to comment.