# 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](https://delta1labs.com/products/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`:

```csharp
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`.

<figure class="my-8"><svg viewBox="0 0 760 330" role="img" aria-label="A ref int field compiles to a field whose signature is FIELD BYREF I4, rendered as int32 ampersand. Two source operations that look alike produce different IL: rebinding the field with equals ref stores the reference with stfld, while writing through the field with plain equals loads the reference with ldfld and then stores indirectly with stind. Glass reconstructs the ref keyword from the stfld-into-byref pattern and omits it for the ldfld-then-stind pattern."><rect x="0" y="0" width="760" height="330" fill="none"></rect><text x="20" y="26" fill="#6366f1" font-size="15" font-weight="bold" font-family="sans-serif">A ref field and its two writes</text><rect x="20" y="40" width="230" height="46" rx="6" fill="none" stroke="#6366f1" stroke-width="1.5"></rect><text x="34" y="60" fill="#64748b" font-size="13" font-family="monospace">ref int _value;</text><text x="34" y="78" fill="#64748b" font-size="11" font-family="sans-serif">field in a ref struct</text><text x="262" y="66" fill="#64748b" font-size="22" font-family="sans-serif">&#8594;</text><rect x="300" y="40" width="440" height="46" rx="6" fill="none" stroke="#0891b2" stroke-width="1.5"></rect><text x="314" y="60" fill="#0891b2" font-size="12" font-family="monospace">.field private int32&amp; _value</text><text x="314" y="78" fill="#0891b2" font-size="11" font-family="monospace">FieldSig: FIELD(06) BYREF(10) I4(08)</text><rect x="20" y="110" width="350" height="110" rx="6" fill="none" stroke="#10b981" stroke-width="1.5"></rect><text x="34" y="132" fill="#10b981" font-size="13" font-weight="bold" font-family="monospace">_value = ref x;   // rebind</text><text x="34" y="156" fill="#64748b" font-size="12" font-family="monospace">ldarg.0</text><text x="34" y="174" fill="#64748b" font-size="12" font-family="monospace">ldarg.1            // an int32&amp;</text><text x="34" y="192" fill="#10b981" font-size="12" font-weight="bold" font-family="monospace">stfld int32&amp; IntRef::_value</text><text x="34" y="212" fill="#64748b" font-size="11" font-family="sans-serif">stores the reference into the field</text><rect x="390" y="110" width="350" height="110" rx="6" fill="none" stroke="#6366f1" stroke-width="1.5"></rect><text x="404" y="132" fill="#6366f1" font-size="13" font-weight="bold" font-family="monospace">_value = 5;       // write through</text><text x="404" y="156" fill="#64748b" font-size="12" font-family="monospace">ldarg.0</text><text x="404" y="174" fill="#6366f1" font-size="12" font-weight="bold" font-family="monospace">ldfld int32&amp; IntRef::_value</text><text x="404" y="192" fill="#64748b" font-size="12" font-family="monospace">ldc.i4.5 ; stind.i4</text><text x="404" y="212" fill="#64748b" font-size="11" font-family="sans-serif">dereferences; field unchanged</text><rect x="20" y="244" width="720" height="68" rx="6" fill="none" stroke="#64748b" stroke-width="1"></rect><text x="34" y="266" fill="#6366f1" font-size="13" font-weight="bold" font-family="sans-serif">How Glass tells them apart</text><text x="34" y="286" fill="#64748b" font-size="12" font-family="sans-serif">stfld into a byref field = ref-reassignment, so emit `= ref`. ldfld of the field then stind/stobj = a write</text><text x="34" y="304" fill="#64748b" font-size="12" font-family="sans-serif">through the reference, so emit plain `=`. The field signature never changes; only the instruction does.</text></svg><figcaption class="text-sm text-muted mt-2">A byref field holds a reference. Storing into it (stfld) rebinds it; loading it and storing indirectly (ldfld + stind) writes through it. Glass recovers the `ref` keyword from which instruction touches the field.</figcaption></figure>

## 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:

```csharp
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:

```csharp
[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&lt;T&gt;

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:

```csharp
// 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:

```csharp
// .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:

```bash
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](https://delta1labs.com/products/glass) and the [docs](https://delta1labs.com/docs/glass/).

