Skip to content
← All posts
· Delta1 Labs BoxingGlass.NETDecompilation.NETDeep Dive

How boxing and unboxing decompile in C#

An implicit conversion from int to object is invisible in C# but allocates on the heap — and the IL says so with a box opcode. This walks through where box, unbox.any and the constrained. prefix come from, why generic code uses constrained. to dodge a boxing allocation, and how Glass.NET reconstructs readable C# while the IL reveals the allocation that the source hides.

An implicit conversion from int to object is one of the quietest expensive things in C#. You write object o = n; — no cast, no ceremony — and a heap allocation happens. The C# says nothing about it. The IL says everything about it, in a single opcode: box. Boxing, its inverse unbox.any, and the constrained. prefix that generic code uses to avoid boxing are a small family of instructions that together explain where the hidden allocations in .NET come from. They are also a good illustration of a decompiler’s job: Glass.NET gives you back the readable C# the author wrote, and the IL view gives you back the allocation the author never typed.

Glass.NET is a free .NET decompiler and assembly inspector built on the ILSpy engine. Everything below is static analysis — it reads the metadata and the method bodies of an assembly you already have; it never loads or runs the target.

The box opcode

Start with the simplest possible boxing conversion:

public static object Wrap(int n) => n;

The return type is object and the argument is int, so a conversion has to happen. In the IL it is explicit:

ldarg.0
box      [System.Runtime]System.Int32
ret

box pops the int, allocates a boxed Int32 on the managed heap, and pushes the reference. That is the whole story of boxing: a value type is copied into a freshly allocated object so a reference-typed slot can hold it. The same opcode appears for a conversion to an interface the value implements, to System.ValueType, to System.Enum, or to dynamic — anywhere a value needs to become a reference.

Glass.NET decompiles Wrap back to return n;, which is exactly the source. The allocation is not visible in that line because it was never visible in the original line either. Flip the same method to the IL view and the box Int32 is right there — the one instruction that turns an innocuous return into an allocation.

Unboxing is a cast

The reverse direction is a cast from object back to a value type:

public static int Unwrap(object o) => (int)o;
ldarg.0
unbox.any [System.Runtime]System.Int32
ret

unbox.any is the modern, convenient form: it extracts the int value from the box and leaves it on the stack, throwing InvalidCastException if o is not really a boxed Int32. It is equivalent to the older pair unbox (which yields a managed pointer into the box without copying) followed by ldobj (which reads the value through that pointer). You will mostly see unbox.any in decompiled output because the C# cast (int)o maps straight onto it; the bare unbox shows up when the source took the address of or mutated a boxed value in place. A decompiler reading unbox.any Int32 turns it back into the (int) cast it came from.

Where boxing hides: string.Format

The conversions above are visible because the types differ by one line. Boxing gets interesting when it is buried inside a library call. A classic case is a composite format string:

public static string Line(int id, bool ok) =>
    string.Format("{0}:{1}", id, ok);

string.Format here binds to the Format(string, object[]) overload, so the two value-type arguments must each become an object. The IL builds the array and boxes as it fills it:

ldstr     "{0}:{1}"
ldc.i4.2
newarr    [System.Runtime]System.Object
dup
ldc.i4.0
ldarg.0
box       [System.Runtime]System.Int32      // id
stelem.ref
dup
ldc.i4.1
ldarg.1
box       [System.Runtime]System.Boolean    // ok
stelem.ref
call      string [System.Runtime]System.String::Format(string, object[])
ret

One array allocation plus two boxes for a single formatting call. The decompiled C# is the clean one-liner you wrote; the cost is in the newarr and the two box opcodes beneath it. Seeing that is often the first step in understanding why a hot logging path allocates more than it looks like it should.

The famous one: Enum.HasFlag

Enum.HasFlag is the canonical surprise. Its signature takes a System.Enum, which is a reference type, so calling it on a value-typed enum boxes — twice:

[Flags] enum Access { Read = 1, Write = 2 }

public static bool CanWrite(Access a) => a.HasFlag(Access.Write);
ldarg.0
box       Access
ldc.i4.2
box       Access
call      instance bool [System.Runtime]System.Enum::HasFlag(class [System.Runtime]System.Enum)
ret

The receiver a is boxed, and the argument Access.Write is boxed. The decompiled source is the tidy a.HasFlag(Access.Write); the IL is where the two allocations announce themselves. (This is exactly why the common advice is to write (a & Access.Write) != 0 in hot code — and if you decompile that version, the box opcodes are simply gone, replaced by an and and a comparison.)

The constrained. prefix: boxing you can avoid

Generic code faces a dilemma. Consider:

public static string Describe<T>(T value) => value.ToString();

At compile time the compiler does not know whether T will be a struct or a class. If it always boxed value to call object.ToString(), every struct would allocate. If it never boxed, reference types would break. The CLR’s answer is the constrained. prefix, which defers the decision to the JIT:

.method public static string Describe<T>(!!T value)
{
  ldarga.s   value           // address of the value, not a copy
  constrained. !!T
  callvirt   instance string [System.Runtime]System.Object::ToString()
  ret
}

Note ldarga — it loads the address of the argument, a managed pointer, rather than the value. The constrained. !!T prefix then tells the JIT how to dispatch through that pointer once T is known:

constrained. !!T + callvirtptr → T::ToString()what is T at run time?value type, overridescall T::ToString()direct call — no boxvalue type, no overridebox T; callvirtone allocationreference typeldind.ref; callvirtdereference, dispatchSame IL body, three JIT outcomes — the prefix is how generic code avoids boxing a struct that overrides the method.

So Describe(new DateTime()) calls DateTime.ToString() directly with no allocation, because DateTime overrides ToString. Describe(someCustomStruct) that does not override ToString boxes once and calls object.ToString(). Describe("hello") dereferences the pointer and does an ordinary virtual call. One IL method body, three behaviours chosen by the JIT — and the whole reason the prefix exists is to keep the first case allocation-free.

Glass.NET reconstructs all three cases as the same value.ToString(), because that is the source. What the IL view adds is the constrained. !!T prefix itself, which is your signal that the call site is generic and that whether it allocates depends entirely on the concrete T. That is a distinction you cannot read off the C# at all.

Why the two views matter together

The pattern across all four examples is the same. The decompiled C# is faithful to what the author wrote — return n;, string.Format(...), a.HasFlag(...), value.ToString(). None of those lines mention an allocation, because the language is designed to make the conversions implicit. The allocations live one layer down, in box, in the newarr/stelem.ref/box sequence, and in the dispatch that constrained. resolves. A decompiler that only ever showed you the C# would be hiding exactly the thing a value-type conversion costs.

That is why reading the two views side by side is the useful habit. Glass.NET reconstructs the shape so the code is legible; the IL view keeps the opcodes verbatim so the allocations are countable. Both are static reads of the same assembly — no execution, nothing instrumented — which makes this a safe way to audit third-party or your own compiled code for boxing you did not intend.

Takeaway

Boxing is invisible in C# by design and explicit in IL by necessity. box marks every value-to-reference conversion, unbox.any marks the cast back, and the constrained. prefix is the mechanism that lets generic code sidestep a boxing allocation when the concrete type permits. When a decompiled method looks allocation-free but your profiler disagrees, open the IL view in Glass.NET and count the box opcodes — the source hid them, but the IL never could.

Try Nebula.NET

Harden your .NET code in minutes — start with the free edition.