DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

How typeof decompiles in C#

Ask a .NET engineer what IL typeof(string) produces and many will guess there is a typeof opcode. There is not. typeof is one of a handful of C# operators that compile to a fixed pair of instructions, and knowing that pair is the whole trick to reading it back out of a stripped assembly.

The real question

When Glass decompiles a method and shows you typeof(Customer), where did that come from? There is no token in the metadata that says "this is a typeof expression." What the compiler actually emitted is a load of a metadata token followed by a specific framework call. The decompiler has to recognise that shape and reverse it — and the type name you see is read directly out of the token operand, not reconstructed from a string. That makes typeof one of the most faithfully recoverable constructs in the language, with a few sharp edges around generics and attributes.

The lowering, shown

Start with the simplest case:

Type t = typeof(string);
Enter fullscreen mode Exit fullscreen mode

The C# compiler emits:

ldtoken    [System.Runtime]System.String
call       class [System.Runtime]System.Type [System.Runtime]System.Type::GetTypeFromHandle(valuetype [System.Runtime]System.RuntimeTypeHandle)
stloc.0
Enter fullscreen mode Exit fullscreen mode

Two instructions carry the meaning. ldtoken takes a metadata token as its inline operand and pushes a RuntimeTypeHandle — a lightweight value-type wrapper around that token. GetTypeFromHandle is the one framework method that converts a handle into a live System.Type. The pair is invariant: the compiler never emits ldtoken of a type followed by anything else for a typeof, and it never produces GetTypeFromHandle any other way from C# source. So Glass can match on it mechanically.

The recovery has two halves. First, pattern-match the instruction pair and collapse it to a single typeof(...) node. Second — and this is the part that makes it exact — resolve the ldtoken operand against the metadata tables to get the type name. For typeof(string) the operand is a TypeRef token (table 0x01) pointing at System.String in the referenced System.Runtime assembly. Glass reads the TypeRef row, follows its ResolutionScope to the assembly reference, and prints the type's C# keyword, string.

typeof lowers to a fixed instruction pair; Glass matches the pair and resolves the token operand back to the exact type name.

Generics are where the token gets interesting

A closed constructed generic forces the operand into a different table. Consider:

Type t = typeof(Dictionary<string, int>);
Enter fullscreen mode Exit fullscreen mode
ldtoken    class [System.Collections]System.Collections.Generic.Dictionary`2<string, int32>
call       class System.Type System.Type::GetTypeFromHandle(valuetype System.RuntimeTypeHandle)
Enter fullscreen mode Exit fullscreen mode

Dictionary<string, int> is not a single row in any type table — it is a constructed type. The compiler encodes it as a TypeSpec (table 0x1B), whose blob is a signature: the generic type Dictionary2 followed by its two type arguments. Glass parses that signature recursively — GENERICINST, then the base type, then the argument count, then each argument's own signature element — and rebuilds Dictionary<string, int> with the arguments in order. The arithmetic backtick in Dictionary2 is the arity marker in metadata; Glass converts it back to angle-bracket syntax.

The unbound case is the one people misread:

Type t = typeof(Dictionary<,>);
Enter fullscreen mode Exit fullscreen mode

Here the ldtoken operand is the open generic definition Dictionary2 itself — a plain TypeRef/TypeDef, no TypeSpec, no arguments. GetTypeFromHandle returns the generic type definition. The only C# syntax that produces an open type in a typeof is the empty-comma form, so Glass prints typeof(Dictionary<,>) — the two empty slots come from the arity 2, not from any stored argument.

Type parameters follow the same pattern but with signature-local tokens. Inside a generic method:

static Type Of<T>() => typeof(T);
Enter fullscreen mode Exit fullscreen mode
ldtoken    !!0
call       class System.Type System.Type::GetTypeFromHandle(valuetype System.RuntimeTypeHandle)
ret
Enter fullscreen mode Exit fullscreen mode

!!0 is the signature encoding for "method generic parameter at index 0." (!0 would be a type generic parameter.) Glass maps that index back to the method's declared type-parameter name, T, and renders typeof(T). If the names were stripped it would fall back to !!0 as a synthetic name, but the structure is intact either way.

How you use this in Glass

In the decompiled C# view the folding is automatic — you see typeof(X) and never the raw pair. The reason to care is when you drop into the IL view (or the CLI's IL output) to verify something. If you see an ldtoken that is not immediately followed by GetTypeFromHandle, that is deliberately not a typeof: ldtoken of a field or method handle feeds RuntimeHelpers.InitializeArray (array literals) or reflection via GetFieldFromHandle / GetMethodFromHandle. Glass keys the fold on the exact callee, so those other uses survive as RuntimeTypeHandle / RuntimeFieldHandle expressions rather than being mislabeled.

From the Glass CLI you can confirm the shape directly:

glass il MyApp.dll --type Catalog --method Describe
Enter fullscreen mode Exit fullscreen mode

and the IL view in the UI highlights the ldtoken operand as a navigable metadata token — click it and Glass jumps to the TypeRef or TypeSpec row it resolves, which is exactly the resolution step the decompiler ran to recover the name.

Where it breaks

The honest caveat is the attribute position. When typeof appears as an attribute argument —

[XmlInclude(typeof(Invoice))]
Enter fullscreen mode Exit fullscreen mode

— there is no ldtoken/GetTypeFromHandle pair at all. Custom-attribute arguments are serialized into the #Blob heap, and a Type argument is stored as its assembly-qualified name string, not as a token. So typeof in an attribute decompiles through a completely different path: Glass reads the attribute blob, parses the serialized type name, and reconstructs typeof(Invoice) from the string. That round-trip can lose the original namespace abbreviation and, for types in other assemblies, surfaces the fully qualified name until Glass simplifies it against the imports.

The second edge is obj.GetType(). It is tempting to think of it as a sibling of typeof, but in IL it is a callvirt to System.Object::GetType with no ldtoken anywhere — it reads the runtime type of an instance. Glass never confuses the two, because the instruction shapes have nothing in common: typeof has a compile-time token, GetType has a virtual call and an instance on the stack.

Takeaway

typeof is a two-instruction idiom — ldtoken plus GetTypeFromHandle — and because the type lives in the token operand rather than in a string, Glass recovers it exactly, generics and type parameters included. The one place the type name is a string is the attribute blob, and that is precisely the one place the recovery is approximate. Knowing which path produced your typeof tells you how much to trust the name you are looking at.

Top comments (0)