How Glass recovers typed references from IL
A TypedReference pairs a managed pointer with a type handle, and the C# keywords __makeref, __refvalue and __reftype compile to three opcodes you almost never see: mkrefany, refanyval and refanytype. Here is what each one does on the stack, why TypedReference is byref-like and unboxable, and how Glass.NET pattern-matches the idioms back to readable C# — plus the fallback when the shape will not round-trip.
Open enough low-level .NET code in a decompiler and you eventually hit a method whose parameter type is typedref and whose body calls opcodes with names you have never typed: mkrefany, refanyval, refanytype. These are the compiled form of three C# keywords — __makeref, __refvalue and __reftype — that almost nobody writes by hand. They exist for one job: passing a reference to a variable, together with that variable’s type, when the type is not known until run time. Reconstructing them cleanly is a good stress test for a decompiler, because the value they move around is one the type system treats as radioactive.
The real question
A TypedReference is not an object and not a plain pointer. It is a pair: a managed pointer (a byref) into some storage, and a RuntimeTypeHandle that records the static type of that storage. That pairing is what lets you hand someone a reference to an int local and have them discover, at run time, that it is an int and write a new value straight back into the original slot — no boxing, no copy.
The cost of that power is that TypedReference is byref-like: because it can point into the stack, the runtime refuses to let it escape. It cannot be boxed, stored in a field or array, used as a generic type argument, or held across an await. So the question for a decompiler is twofold: how do you recognise the three opcodes that build and read one, and how do you reconstruct readable C# around a value you are forbidden from stashing in a temporary the way you would with anything else?
One small example, all three keywords
Here is a method that takes a TypedReference, checks its run-time type, and — if it is an int — increments the referenced variable in place. The caller never passes the type; it is carried inside the reference.
using System;
static class Reflect
{
static void BumpIfInt(TypedReference tr)
{
if (__reftype(tr) == typeof(int))
__refvalue(tr, int) += 1;
}
static int Demo()
{
int n = 41;
TypedReference tr = __makeref(n);
BumpIfInt(tr);
return n; // 42 — the write landed back in the local
}
}
Three keywords, three jobs. __makeref(n) builds a reference to the local n. __reftype(tr) asks the reference what type it carries. __refvalue(tr, int) opens the reference as an int lvalue — so += 1 writes through it, and because the reference aliases n, Demo returns 42.
What each opcode does on the stack
Each keyword is exactly one IL opcode. Here is Demo, where the reference is built:
.method private hidebysig static int32 Demo() cil managed
{
.locals init (int32 n, typedref tr)
IL_0000: ldc.i4.s 41
IL_0002: stloc.0
IL_0003: ldloca.s n
IL_0005: mkrefany [System.Runtime]System.Int32
IL_000a: stloc.1
IL_000b: ldloc.1
IL_000c: call void Reflect::BumpIfInt(typedref)
IL_0011: ldloc.0
IL_0012: ret
}
ldloca.s n pushes a managed pointer to the local. mkrefany (0xC6) pops that pointer and pushes a TypedReference, stamping it with the type token in its operand — here System.Int32. Note the local is declared typedref: that is ELEMENT_TYPE_TYPEDBYREF (0x16) in the signature blob, the same element the parameter of BumpIfInt uses.
And here is the consumer, where the reference is read two different ways:
.method private hidebysig static void BumpIfInt(typedref tr) cil managed
{
IL_0000: ldarg.0
IL_0001: refanytype
IL_0003: call class [System.Runtime]System.Type [System.Runtime]System.Type::GetTypeFromHandle(valuetype [System.Runtime]System.RuntimeTypeHandle)
IL_0008: ldtoken [System.Runtime]System.Int32
IL_000d: call class [System.Runtime]System.Type [System.Runtime]System.Type::GetTypeFromHandle(valuetype [System.Runtime]System.RuntimeTypeHandle)
IL_0012: call bool [System.Runtime]System.Type::op_Equality(class [System.Runtime]System.Type, class [System.Runtime]System.Type)
IL_0017: brfalse.s IL_0024
IL_0019: ldarg.0
IL_001a: refanyval [System.Runtime]System.Int32
IL_001f: dup
IL_0020: ldind.i4
IL_0021: ldc.i4.1
IL_0022: add
IL_0023: stind.i4
IL_0024: ret
}
refanytype (0xFE 0x1D) pops the TypedReference and pushes its RuntimeTypeHandle; the GetTypeFromHandle call that follows turns it into a System.Type so it can be compared with typeof(int). refanyval (0xC2) pops the reference and pushes the managed pointer it carries — but only after checking that the type token in its operand matches the type stamped into the reference; a mismatch throws InvalidCastException. That pointer is then a normal int&, so dup / ldind.i4 / ldc.i4.1 / add / stind.i4 is the usual read-modify-write of a +=, writing straight back through the reference into n.
How Glass turns the opcodes back into keywords
The mapping is one-to-one, which is the good news, but Glass reconstructs the expression shape around each opcode, not just the opcode name:
mkrefany Tfed by an address-of instruction (ldloca,ldflda,ldelema,ldsflda) becomes__makeref(<that lvalue>). Glass walks back to the source of the managed pointer and names the variable, field or element it addresses.refanyval Tbecomes__refvalue(tr, T), and the surrounding opcodes decide whether it is a read or a write. Followed byldind/ldobjit is a value read; thedup … stindidiom above is reconstructed as the compound assignment__refvalue(tr, int) += 1; a barestind/stobjbecomes a plain assignment. The type tokenTis preserved verbatim, becauserefanyvalis type-invariant — there is no widening or covariance to fold away.refanytypefollowed byGetTypeFromHandlebecomes__reftype(tr), collapsing the two-step handle-to-Typedance that the C# keyword hides.
Doing it from the CLI
You do not need the window. Point glass export at the assembly and pull the member in IL, then in C#:
$ glass export ./Lowlevel.dll --member "M:Reflect.BumpIfInt(System.TypedReference)" --il
$ glass export ./Lowlevel.dll --member "M:Reflect.BumpIfInt(System.TypedReference)"
The first dumps the body with refanytype, refanyval and the GetTypeFromHandle calls intact; the second shows the reconstructed C#, where Glass has already collapsed those into __reftype(tr) and __refvalue(tr, int) += 1. Because these keywords cluster in interop and reflection helpers, this is the quick way to confirm what a shim actually reads or writes by reference — all static, nothing executed.
Caveats and when it breaks
The honest limits follow from the type’s own rules. __makeref needs a genuine addressable lvalue: when the managed pointer feeding mkrefany comes from ldloca/ldflda/ldelema, Glass can name the variable and print __makeref(x). When it comes from pointer arithmetic, a ref-returning call, or a ref local that has been reassigned, there is no single source variable to spell, and Glass shows the managed-pointer expression or the raw mkrefany rather than fabricate an lvalue that would not recompile.
refanyval is type-invariant by design — it checks the stored type against its operand token and throws on any mismatch — so Glass keeps the exact T it finds and never substitutes a base type or an implicit conversion. And not every TypedReference is born from mkrefany: the reflection API TypedReference.MakeTypedReference(object, FieldInfo[]) produces one from a boxed object and a field path, so Glass renders that as the ordinary method call it is, not as __makeref.
Finally, because TypedReference is byref-like, Glass is constrained in how it may reshape the surrounding code: it cannot hoist the value into a field, an array element, or a captured closure variable to tidy up control flow, because the type system forbids exactly those moves. The decompiled C# therefore tends to keep the reference close to where it is made and read, which is usually faithful to how the code was written in the first place.
Takeaway
TypedReference is a managed pointer paired with a type handle — a small, byref-like value the type system guards closely because it can alias the stack. The three keywords that create and read one, __makeref, __refvalue and __reftype, compile to mkrefany, refanyval and refanytype, with typedref (0x16) marking the type in signatures. Glass.NET recognises each opcode in context — the address-of before mkrefany, the ldind/stind after refanyval, the GetTypeFromHandle after refanytype — and reconstructs the readable keyword form, falling back to the raw opcode or the reflection API only when the shape genuinely will not round-trip. It is a tiny corner of the instruction set, but a clean example of how decompiling well means reading the opcodes and the expression they sit inside. Grab the free build from the Glass.NET download page and point it at the next reflection helper you need to understand.
Try Nebula.NET
Harden your .NET code in minutes — start with the free edition.