# How nullable value types decompile in C#


Everything the C# language lets you do with `int?` is a lie the compiler tells on behalf of a struct. There is no null in an `int?`. There is no special "nullable integer" type the CLR knows how to add. There is `System.Nullable<int>` — two fields, sixteen bytes, a value type like any other — and a compiler that rewrites `a + b`, `a == null`, `a ?? 5` and `(object)a` into calls on that struct so thoroughly that the operators you typed never reach the IL. Reading an obfuscated or symbol-less assembly that uses nullable arithmetic means reading those rewrites, and a decompiler that renders them literally produces code that is correct, compilable, and unreadable.

This post follows each lowering through the IL and back out, and shows what [Glass.NET](https://delta1labs.com/products/glass/) has to recognise to give you the line you wrote.

## `int?` is in the signature blob, not in an attribute

First the easy part, because it is the opposite of a trap readers of [nullable reference types](https://delta1labs.com/blog/decompile-nullable-reference-types/) have learned to expect. `string?` leaves the type alone and records nullability in `[Nullable]` attributes — compile-time annotations the runtime ignores. `int?` is a *different type*: the generic struct `Nullable<T>` instantiated over `int`, and it appears as such in every signature:

```
.method public hidebysig static valuetype [System.Runtime]System.Nullable`1<int32>
        Add(valuetype [System.Runtime]System.Nullable`1<int32> a,
            valuetype [System.Runtime]System.Nullable`1<int32> b) cil managed
```

A decompiler prints `int?` for ``valuetype System.Nullable`1<int32>`` by the same rule it prints `int` for `System.Int32` — the language's shorthand for a known type. No attribute is consulted; nothing can be stripped that would lose it. Metadata hardening that removes `[Nullable]` annotations leaves `int?` completely intact, because the information was never an annotation.

The struct itself is two fields and a handful of members, and those members are the entire vocabulary of every lowering that follows:

```csharp
public struct Nullable<T> where T : struct
{
    private readonly bool hasValue;
    internal T value;
    public Nullable(T value);              // the "has a value" constructor
    public bool HasValue { get; }
    public T Value { get; }                // throws InvalidOperationException when !hasValue
    public T GetValueOrDefault();          // returns value unconditionally — no check, no throw
}
```

`default(Nullable<T>)` — both fields zero — is what the language calls `null`.

## Lifted arithmetic: a conjunction, two `GetValueOrDefault`s, and a `newobj`

Take the method whose signature appears above:

```csharp
static int? Add(int? a, int? b) => a + b;
```

The `+` on two `int?` values is a *lifted* operator: the result is null if either operand is null, otherwise the sum. The compiler emits that rule directly:

```
  .locals init (valuetype Nullable`1<int32> V_0,
                valuetype Nullable`1<int32> V_1,
                valuetype Nullable`1<int32> V_2)
  IL_0000: ldarg.0
  IL_0001: stloc.0                                   // copy a to a temp (operands evaluated once)
  IL_0002: ldarg.1
  IL_0003: stloc.1                                   // copy b
  IL_0004: ldloca.s   V_0
  IL_0006: call       instance bool Nullable`1<int32>::get_HasValue()
  IL_000b: ldloca.s   V_1
  IL_000d: call       instance bool Nullable`1<int32>::get_HasValue()
  IL_0012: and                                       // both have a value?
  IL_0013: brtrue.s   IL_0020
  IL_0015: ldloca.s   V_2
  IL_0017: initobj    Nullable`1<int32>              // the null result: default(Nullable<int>)
  IL_001d: ldloc.2
  IL_001e: ret
  IL_0020: ldloca.s   V_0
  IL_0022: call       instance !0 Nullable`1<int32>::GetValueOrDefault()
  IL_0027: ldloca.s   V_1
  IL_0029: call       instance !0 Nullable`1<int32>::GetValueOrDefault()
  IL_002e: add
  IL_002f: newobj     instance void Nullable`1<int32>::.ctor(!0)
  IL_0034: ret
```

Three details are worth noticing, because they are what a decompiler keys on:

- The operands are copied to **temporaries** first, so each is evaluated exactly once even though it is read twice (once for `HasValue`, once for the value). A hand-written version would usually not bother.
- The value is read with **`GetValueOrDefault`**, not `Value`. `HasValue` was just checked, so the re-check inside `Value` would be redundant and its throw path unreachable; `GetValueOrDefault` is a plain field read. Seeing `GetValueOrDefault` immediately after a `HasValue` guard is the single strongest signal that you are looking at compiler output rather than source.
- The null result is **`initobj`**, not a call — there is no "null constructor"; the null state is the struct zeroed.

Render that literally and you get:

```csharp
// faithful to the IL, and not what anyone wrote:
int? num = a, num2 = b;
return (num.HasValue & num2.HasValue)
    ? new int?(num.GetValueOrDefault() + num2.GetValueOrDefault())
    : null;
```

That compiles and is semantically exact. It is also three lines, two temporaries and four calls for a single `+`. Glass recognises the whole shape — temporaries, conjunction of `HasValue`, a pair of `GetValueOrDefault` feeding one binary operator, `newobj` on the true arm and `initobj` on the false — and emits `a + b`. The same template covers every lifted arithmetic, bitwise and shift operator; only the instruction between the two `GetValueOrDefault` calls changes.

<figure class="my-8"><svg viewBox="0 0 700 300" role="img" aria-label="Diagram of how a lifted addition on two nullable ints is lowered and refolded. At the top, the source a plus b on int? operands. Below it, the compiler lowering: copy a and b to temporaries; call HasValue on each and AND them; on the false branch initobj a Nullable int which is the null result; on the true branch call GetValueOrDefault on each temporary, add, and newobj Nullable int. At the bottom, the decompiler recognises that entire shape as one unit and emits a plus b again. A side note lists the signals: GetValueOrDefault right after a HasValue guard, operands copied to temporaries, and initobj for null." style="width:100%;height:auto"><defs><style>.ti{font:600 12px system-ui;fill:#1547e0}.h{font:600 11px system-ui;fill:#0f172a}.x{font:10px system-ui;fill:#475569}.mono{font:10px ui-monospace,Consolas,monospace;fill:#1e293b}.src{fill:#eef4ff;stroke:#8eb4ff}.il{fill:#f1f5f9;stroke:#cbd5e1}.nul{fill:#fee2e2;stroke:#f87171}.val{fill:#dcfce7;stroke:#4ade80}.note{fill:#fef3c7;stroke:#fbbf24}.ar{stroke:#64748b;stroke-width:1.3;fill:none;marker-end:url(#a)}</style><marker id="a" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 z" fill="#64748b"/></marker></defs><text class="ti" x="12" y="18">Lifted + : lowering and refolding</text><rect class="src" x="12" y="32" width="200" height="40" rx="5"/><text class="h" x="20" y="50">source</text><text class="mono" x="20" y="66">int? r = a + b;</text><rect class="il" x="12" y="92" width="200" height="60" rx="5"/><text class="h" x="20" y="110">guard</text><text class="mono" x="20" y="128">V_0=a; V_1=b</text><text class="mono" x="20" y="144">V_0.HasValue & V_1.HasValue</text><rect class="nul" x="12" y="176" width="200" height="50" rx="5"/><text class="h" x="20" y="194">false arm → null</text><text class="mono" x="20" y="212">initobj Nullable<int></text><rect class="val" x="250" y="176" width="232" height="50" rx="5"/><text class="h" x="258" y="194">true arm → value</text><text class="mono" x="258" y="212">GetValueOrDefault ×2; add; newobj</text><rect class="src" x="250" y="32" width="232" height="40" rx="5"/><text class="h" x="258" y="50">decompiled (Glass)</text><text class="mono" x="258" y="66">int? r = a + b;</text><path class="ar" d="M112,72 L112,92"/><path class="ar" d="M112,152 L112,176"/><path class="ar" d="M212,122 C240,122 240,200 250,200"/><path class="ar" d="M366,176 L366,72"/><path class="ar" d="M112,226 C112,250 366,250 366,226" stroke-dasharray="4 3"/><rect class="note" x="510" y="32" width="178" height="194" rx="5"/><text class="h" x="520" y="52">signals of a lowering</text><text class="x" x="520" y="76">GetValueOrDefault read</text><text class="x" x="520" y="92">right after a HasValue</text><text class="x" x="520" y="108">guard (never .Value)</text><text class="x" x="520" y="132">operands copied to</text><text class="x" x="520" y="148">temporaries first</text><text class="x" x="520" y="172">initobj — not a call —</text><text class="x" x="520" y="188">for the null result</text><text class="x" x="520" y="212">one operator per shape</text><rect class="il" x="12" y="250" width="676" height="38" rx="5"/><text class="x" x="22" y="273">Rendered literally: (V_0.HasValue & V_1.HasValue) ? new int?(V_0.GetValueOrDefault() + V_1.GetValueOrDefault()) : null</text></svg></figure>

## Lifted equality is a different shape

Comparison is not lowered the same way, because the rule is different: two nulls are *equal*, and a null is unequal to any value. The compiler produces a branch-free expression for it:

```csharp
static bool Same(int? a, int? b) => a == b;
```

```
  IL_0004: ldloca.s   V_0
  IL_0006: call       instance !0 Nullable`1<int32>::GetValueOrDefault()
  IL_000b: ldloca.s   V_1
  IL_000d: call       instance !0 Nullable`1<int32>::GetValueOrDefault()
  IL_0012: ceq                                       // values equal (both 0 when both null)
  IL_0014: ldloca.s   V_0
  IL_0016: call       instance bool Nullable`1<int32>::get_HasValue()
  IL_001b: ldloca.s   V_1
  IL_001d: call       instance bool Nullable`1<int32>::get_HasValue()
  IL_0022: ceq                                       // same has-value state
  IL_0024: and
  IL_0025: ret
```

That is `(a.GetValueOrDefault() == b.GetValueOrDefault()) & (a.HasValue == b.HasValue)`. Walk the cases: both null → `0 == 0` and `false == false` → true. One null, one `5` → `0 == 5` is false → false. Both `5` → true. Note that `GetValueOrDefault` is called here *without* a prior `HasValue` guard — it is being used precisely because it is safe on a null — so the "`GetValueOrDefault` after guard" signal from the arithmetic case does not apply, and the decompiler needs a second template for this shape. `<`, `>`, `<=`, `>=` lower to the value comparison ANDed with `a.HasValue & b.HasValue` (two nulls are *not* less-than each other), which is a third variant of the same idea.

## `== null`, `??`, and the pattern `is int v`

The simpler forms have simpler lowerings, each of which is a single-template match:

```csharp
bool IsNull(int? a) => a == null;        // ldarga a; call get_HasValue; ldc.i4.0; ceq
int  OrFive(int? a) => a ?? 5;           // a.HasValue ? a.GetValueOrDefault() : 5
int  Force (int? a) => (int)a;           // ldarga a; call get_Value   — the only place Value appears
bool Test  (int? a) => a is int v && v > 0;   // a.HasValue && a.GetValueOrDefault() > 0
```

`== null` never compares a reference: there is no reference. It is `!a.HasValue`, and `!= null` is `a.HasValue`. `??` becomes a conditional on `HasValue` with `GetValueOrDefault` on the value arm — again not `Value`, because the guard already ran. The explicit cast `(int)a` is the **only** lowering that calls `get_Value`, because it is the only one whose contract is to throw when there is nothing there; a decompiler can use that as a tell. And the type pattern `a is int v` over a nullable is lowered to `HasValue` plus `GetValueOrDefault` into `v`, with no `isinst` anywhere — the runtime type test the pattern looks like never happens, because the compiler already knows what the struct contains.

## The box that erases `Nullable<T>`

Everything so far is the compiler rewriting language into calls. Boxing is different: here the *runtime* does something special, and the IL says less than it seems to.

```csharp
object Box(int? a)   => a;              // box valuetype Nullable`1<int32>
int?   Unbox(object o) => (int?)o;      // unbox.any valuetype Nullable`1<int32>
```

Boxing an ordinary struct copies it to the heap behind an object header. The `box` instruction applied to `Nullable<T>` does **not** do that. The runtime checks `hasValue`: if it is false, the result is a **null reference**; if it is true, the result is a **boxed `T`** — a heap object of type `System.Int32`, byte-for-byte identical to boxing a plain `int`. `Nullable<int>` itself never reaches the heap. The consequences are visible from C#:

```csharp
object o = (int?)5;
o.GetType()            // typeof(int) — not Nullable<int>
o is int               // true
o is int?              // true — same object satisfies both
object n = (int?)null; // n == null; there is no "boxed empty nullable"
```

`unbox.any Nullable<int32>` is the mirror image: given a boxed `int` it constructs a `Nullable<int>` with a value; given a **null reference** it produces an *empty* `Nullable<int>` instead of throwing the `NullReferenceException` that `unbox.any` on any other value type would throw. So `(int?)o` is the one cast in C# that quietly turns `null` into a value-type default.

For a decompiler this is a case of *not* inventing code. The `box` and `unbox.any` instructions name `Nullable<int32>` in their type operand, and the temptation is to render them as a conversion call or a `new int?(…)`. The author wrote a plain implicit conversion and a plain cast; the special behaviour lives inside the runtime's implementation of two ordinary instructions, and the right output is `object o = a;` and `(int?)o`, nothing more.

## What a decompiler gets wrong, and why it matters

Three failure modes show up in practice, and they are all versions of rendering the lowering instead of the language:

1. **The `HasValue`/`GetValueOrDefault` dance printed in full** — correct, verbose, and a reliable sign the tool has no lifted-operator templates. A method with six nullable additions becomes forty lines of temporaries.
2. **`new int?(x)` where the source had `x`** — the implicit conversion from `int` to `int?` is a `newobj` in the IL, and printing the constructor call is faithful but noisy. Glass emits the conversion implicitly wherever the target type makes it unambiguous.
3. **A conversion call around `box`/`unbox.any`** — inventing a method that is not in the IL to explain behaviour that is in the runtime.

The reason these matter beyond aesthetics is that nullable arithmetic clusters in exactly the code a reader is usually trying to understand — optional configuration, financial calculations with "not set" states, pattern-heavy domain logic — and the lowering multiplies its length by three or four. A decompiler that folds the templates back gives you the author's five lines; one that does not gives you a page of struct calls that all look the same.

The underlying lesson is the same one that governs [`?.` and `??`](https://delta1labs.com/blog/decompile-null-conditional-coalescing/) and [`foreach`](https://delta1labs.com/blog/decompile-foreach-enumerator-try-finally-for-loop/): the C# compiler lowers language features into ordinary IL over ordinary types, and the decompiler's job is to know every one of those shapes well enough to run them backwards. `Nullable<T>` is unusual only in how completely it disappears — into a struct on the way in, and into a plain boxed `int` or a null on the way out.

