# How a conditional ref expression decompiles


Write `cond ? a : b` and you get a value — a copy of whichever operand won. Write `cond ? ref a : ref b` and you get something stranger: a *reference* to whichever variable won, an lvalue you can assign through. `(cond ? ref a : ref b) = 5` stores 5 into either `a` or `b`, decided at runtime. This is the conditional ref expression, added in C# 7.2, and it is how you write a branch that selects *storage* rather than data. Decompile it and the surprise is how little separates it from an ordinary ternary in the IL — the branch is byte-for-byte the same shape. The difference is one instruction per arm and one stack type at the merge, and a decompiler that misses it will hand you two assignments where you wrote one expression. This post shows the mechanism and what [Glass](https://delta1labs.com/products/glass) recovers.

## The real question

A ternary compiles to a branch: test the condition, jump to one arm or the other, and merge. Both the value form and the ref form do exactly that. So the branch structure cannot be what distinguishes them — and indeed it is not. What distinguishes them is the *type that lands on the evaluation stack at the merge point*. A value ternary leaves a value there; a ref ternary leaves a managed pointer. Everything downstream — whether the result is copied, dereferenced, or returned by ref — follows from that one difference. The question a decompiler must answer is therefore narrow and exact: at the point where the two arms of this conditional converge, is the stack slot a value or a managed reference? Get that right and the `ref` ternary reconstructs cleanly; get it wrong and you print a value ternary that silently loses the lvalue.

## The value ternary, as a baseline

Start with the ordinary form so the contrast is sharp:

```csharp
static int PickValue(bool pick, int x, int y)
    => pick ? x : y;
```

The compiler emits the obvious branch, and each arm pushes a *value*:

```
ldarg.0            // pick
brfalse.s  IL_L1
ldarg.1            // x  (the value)
br.s       IL_L2
IL_L1:
ldarg.2            // y  (the value)
IL_L2:
ret                // returns int32
```

At `IL_L2` the stack holds an `int32`. The method returns it. Nothing here is a reference; `x` and `y` were copied onto the stack the instant they were loaded.

## The ref ternary

Now select storage instead. The two arms each load the *address* of a variable, and the method returns by reference:

```csharp
static ref int PickRef(bool pick, ref int x, ref int y)
    => ref (pick ? ref x : ref y);
```

```
ldarg.0            // pick
brfalse.s  IL_L1
ldarg.1            // ref x  (a managed pointer, int32&)
br.s       IL_L2
IL_L1:
ldarg.2            // ref y  (a managed pointer, int32&)
IL_L2:
ret                // returns int32&
```

The skeleton is identical to `PickValue` — same `brfalse.s`, same `br.s`, same merge label. Only the return signature changed from `int32` to `int32&`, and the stack slot at `IL_L2` now holds a managed reference. Here the arms are already byref parameters, so loading them is a plain `ldarg`. The clearer signal appears when the operands are locals or fields, because then the compiler must take their address explicitly:

```csharp
static void WriteChosen(bool pick)
{
    int x = 10, y = 20;
    ref int slot = ref (pick ? ref x : ref y);
    slot = 99;                 // writes to x or y
}
```

```
ldc.i4.s   10
stloc.0            // x
ldc.i4.s   20
stloc.1            // y
ldarg.0            // pick
brfalse.s  IL_L1
ldloca.s   0       // &x  (address of local x)
br.s       IL_L2
IL_L1:
ldloca.s   1       // &y  (address of local y)
IL_L2:
stloc.2            // slot : int32&
ldloc.2
ldc.i4.s   99
stind.i4           // *slot = 99  — writes through to x or y
ret
```

There it is in the open. The value ternary pushed `ldloc` in each arm; the ref ternary pushes `ldloca`. The value ternary converged to an `int32`; the ref ternary converges to an `int32&` that is stored into a byref local and then written *through* with `stind.i4`. Change nothing but those two facts — the address-taking leaf and the byref merge type — and you have turned a value selection into a storage selection.

<figure class="my-8"><svg viewBox="0 0 780 340" role="img" aria-label="A value ternary and a ref ternary share one branch skeleton: a brfalse that selects an arm and a br that merges. The arms are what differ. The value ternary loads values with ldloc, so the merge point holds an int32. The ref ternary loads addresses with ldloca, so the merge point holds a managed reference int32-ampersand. Glass reads the byref stack type at the convergence to emit a conditional ref expression bound to a ref local or ref return, while a value merge stays an ordinary ternary."><rect x="0" y="0" width="780" height="340" fill="none"></rect><text x="20" y="26" fill="#6366f1" font-size="15" font-weight="bold" font-family="sans-serif">One branch shape, two stack types</text><rect x="20" y="40" width="350" height="150" rx="6" fill="none" stroke="#6366f1" stroke-width="1.5"></rect><text x="34" y="60" fill="#6366f1" font-size="12" font-weight="bold" font-family="monospace">v = pick ? x : y;</text><text x="34" y="84" fill="#64748b" font-size="12" font-family="monospace">ldarg.0        ; pick</text><text x="34" y="102" fill="#64748b" font-size="12" font-family="monospace">brfalse.s L1</text><text x="34" y="120" fill="#6366f1" font-size="12" font-weight="bold" font-family="monospace">ldloc.0        ; x  (value)</text><text x="34" y="138" fill="#64748b" font-size="12" font-family="monospace">br.s L2</text><text x="34" y="156" fill="#6366f1" font-size="12" font-weight="bold" font-family="monospace">L1: ldloc.1    ; y  (value)</text><text x="34" y="180" fill="#6366f1" font-size="12" font-weight="bold" font-family="sans-serif">L2: stack type = int32</text><rect x="410" y="40" width="350" height="150" rx="6" fill="none" stroke="#10b981" stroke-width="1.5"></rect><text x="424" y="60" fill="#10b981" font-size="12" font-weight="bold" font-family="monospace">r = ref(pick ? ref x : ref y);</text><text x="424" y="84" fill="#64748b" font-size="12" font-family="monospace">ldarg.0        ; pick</text><text x="424" y="102" fill="#64748b" font-size="12" font-family="monospace">brfalse.s L1</text><text x="424" y="120" fill="#10b981" font-size="12" font-weight="bold" font-family="monospace">ldloca.s 0     ; &amp;x  (address)</text><text x="424" y="138" fill="#64748b" font-size="12" font-family="monospace">br.s L2</text><text x="424" y="156" fill="#10b981" font-size="12" font-weight="bold" font-family="monospace">L1: ldloca.s 1 ; &amp;y  (address)</text><text x="424" y="180" fill="#10b981" font-size="12" font-weight="bold" font-family="sans-serif">L2: stack type = int32&amp;</text><rect x="20" y="206" width="740" height="118" rx="6" fill="none" stroke="#64748b" stroke-width="1"></rect><text x="34" y="228" fill="#6366f1" font-size="13" font-weight="bold" font-family="sans-serif">How Glass tells them apart</text><text x="34" y="250" fill="#64748b" font-size="12" font-family="sans-serif">Same skeleton (brfalse + br to a merge). The leaves decide everything: ldloc pushes a value, while</text><text x="34" y="270" fill="#64748b" font-size="12" font-family="sans-serif">ldloca / ldflda / ldarga pushes a managed reference. When both arms converge to a byref stack slot</text><text x="34" y="290" fill="#64748b" font-size="12" font-family="sans-serif">that is stored into a ref local or returned by ref, Glass emits a conditional ref expression —</text><text x="34" y="310" fill="#64748b" font-size="12" font-family="sans-serif">ref (cond ? ref a : ref b). A value merge stays an ordinary ternary.</text></svg><figcaption class="text-sm text-muted mt-2">The branch is the same for both. A value ternary loads values and merges to an <code>int32</code>; a ref ternary loads addresses and merges to an <code>int32&amp;</code>. Glass reconstructs the <code>ref</code> ternary from the byref stack type at the convergence.</figcaption></figure>

## Where the reference goes next

The byref value left on the stack by a ref ternary is consumed in one of exactly three ways, and each is a confirming signal Glass reads together with the convergence:

- **Bound to a `ref` local** — `stloc` into a slot whose type is `int32&`, as in `WriteChosen` above. Glass renders `ref int slot = ref (…)`.
- **Written or read through** — a following `stind`/`stobj` means the expression was an assignment target (`(cond ? ref a : ref b) = v`); a following `ldind`/`ldobj` means its value was read.
- **Returned by reference** — the enclosing method's return signature is `int32&` and the merge flows straight into `ret`, as in `PickRef`. Glass renders `ref int PickRef(…) => ref (…)`.

In every case the recovered C# keeps the single expression you wrote. A decompiler that reconstructs purely from control flow, without tracking the stack *type*, is tempted to split the branch into two statements — `if (pick) slot = ref x; else slot = ref y;` — which is not what you wrote and, for an assignment target, does not even type-check the same way. Reading the byref merge is what keeps the expression whole.

## Lifetime and ref-safety

The compiler also enforces that both arms are *ref-safe to the same scope*: the chosen reference may not outlive the shorter-lived of the two operands. That analysis is pure compile-time bookkeeping and leaves no IL of its own — there is no attribute on a conditional ref expression. So Glass does not reconstruct ref-safety from a marker; it reconstructs the expression from the stack shape and lets the C# compiler re-check the lifetimes when the exported source is rebuilt. This is why exporting a method that returns `ref (cond ? ref x : ref y)` round-trips only when the operands are genuinely returnable by ref — the same rule the original author had to satisfy.

## How to use it

Point Glass at the assembly and read the method; the conditional ref expression comes back whole, with the `ref` on each arm and on the result:

```bash
glass decompile Buffers.dll --type Chooser
glass decompile Buffers.dll --type Chooser --il   # see ldloca vs ldloc at the arms
```

The IL view is where the mechanism is legible: the two arms show `ldloca`/`ldflda`/`ldarga` rather than `ldloc`/`ldfld`/`ldarg`, and the instruction that consumes the merge — `stloc` into a byref local, a `stind`/`ldind`, or a `ret` from a byref-returning method — tells you how the reference was used. Reading the recovered C# beside the IL is the fastest way to confirm that a single `ref (… ? ref … : ref …)` really was one expression and not a pair of branches. Exporting the type to a buildable project emits the expression and the `ref` return or `ref` local it feeds, so the round-tripped source compiles under the same ref-safety rules.

## When it breaks

The recovery leans on two things being intact: address-producing leaves and a byref convergence consumed as an lvalue. An optimizer that proves the condition constant will fold the ternary away and drop one arm, leaving a single address with no branch — correct output, but no ternary to reconstruct because there genuinely is none. Hand-written or obfuscated IL can reshape the selection into something that is not a clean two-arm merge — a jump table, duplicated tails, a reference round-tripped through a temporary — and when the byref convergence is no longer visible, Glass shows the branch and the indirect load or store as they are rather than inventing a `ref` ternary. That is the honest limit: the IL still describes the memory operations exactly; it is the single-expression intent that thins out.

## Takeaway

A conditional ref expression is a ternary that selects storage instead of a value, and in the IL it is almost indistinguishable from an ordinary ternary — same branch, same merge. The one difference that matters is the type at the convergence: `ldloca`-style leaves push a managed reference, so the merge slot is `int32&` rather than `int32`, and that slot is then bound to a `ref` local, written through with `stind`, or returned by ref. Glass reconstructs the whole expression from that byref convergence, so `ref (cond ? ref a : ref b)` reads back as the single lvalue-selecting expression you wrote, not as two split branches. Glass is a free .NET decompiler; see [Glass](https://delta1labs.com/products/glass) and the [docs](https://delta1labs.com/docs/glass/).

