DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Edited on Originally published at delta1labs.com

Decompiling the `with` expression: how Glass.NET rebuilds record clone sites

A with expression is one of the more magical-looking pieces of modern C#: you take an immutable record, write original with { Price = 9.99m }, and get a fresh copy with one field changed and everything else intact. Non-destructive mutation. But there is no with opcode, no "clone this but change that" instruction in the CLR. By the time the compiler is done, the whole expression has become a plain virtual method call followed by a few field stores. Rebuilding the with keyword from that shape is a small, precise pattern-match — and it is a good way to see how Glass.NET, the free .NET decompiler, reconstructs language features that exist only as conventions in the metadata.

This post walks one with site all the way down to IL and back up to C#. If you want the mechanics of the record declaration itself — EqualityContract, value equality, PrintMembers — that is a separate fingerprint; here we care only about the clone call site.

The source

Start with a tiny record and a single non-destructive update:

public record Product(string Name, decimal Price, int Stock);

public static class Catalog
{
    public static Product Discount(Product p, decimal newPrice) =>
        p with { Price = newPrice, Stock = p.Stock - 1 };
}
Enter fullscreen mode Exit fullscreen mode

Discount returns a new Product that shares Name, takes newPrice, and decrements Stock — without ever mutating p. Two things have to happen under the hood: the object must be copied, then the two named members must be overwritten on the copy. That is exactly what the IL shows.

What the compiler emits

The record itself gains two synthesized members that make with possible: a protected copy constructor that clones every field, and a virtual clone method the C# compiler names <Clone>$ (the angle brackets guarantee you can never collide with it in source). The clone method just calls the copy constructor:

// Synthesized on the record — shown here with readable names
protected Product(Product original)
{
    Name  = original.Name;
    Price = original.Price;
    Stock = original.Stock;
}

public virtual Product <Clone>$() => new Product(this);
Enter fullscreen mode Exit fullscreen mode

The with expression in Discount compiles to a callvirt of <Clone>$, then a store into each property named inside the braces. Here is the method body as ildasm/Glass shows it:

.method public hidebysig static
    class Product Discount (class Product p, valuetype [System.Runtime]System.Decimal newPrice) cil managed
{
    .maxstack 3
    .locals init (class Product V_0)

    IL_0000: ldarg.0                       // p
    IL_0001: callvirt   instance class Product Product::'<Clone>$'()
    IL_0006: stloc.0                        // V_0 = clone of p
    IL_0007: ldloc.0
    IL_0008: ldarg.1                        // newPrice
    IL_0009: callvirt   instance void Product::set_Price(valuetype [System.Runtime]System.Decimal)
    IL_000e: ldloc.0
    IL_000f: ldarg.0                        // p
    IL_0010: callvirt   instance int32 Product::get_Stock()
    IL_0015: ldc.i4.1
    IL_0016: sub
    IL_0017: callvirt   instance void Product::set_Stock(int32)
    IL_001c: ldloc.0
    IL_001d: ret
}
Enter fullscreen mode Exit fullscreen mode

Read it top to bottom and the shape is unmistakable: one callvirt to a method named <Clone>$, its result parked in a temporary, then a sequence of property setter calls on that same temporary, and finally the temporary is returned. The setters are set_Price and set_Stock — the init-only setters of the record, callable here because the copy constructor and with lowering run in an initialization context.

The pattern Glass keys on

Glass does not look for a flag that says "this was a with." There is no such flag. It matches the structural signature of the lowered expression:



Recognizing a with expression in IL

IL sequence
callvirt <Clone>$()
stloc V_0
ldloc V_0
... set_Price
ldloc V_0
... set_Stock
ldloc V_0 ; ret

Match test
callee is compiler
method named
<Clone>$ ?
temp only mutated
by init setters?

Reconstructed C#
p with {
Price = newPrice,
Stock = p.Stock - 1
}



No with opcode exists — the keyword is inferred from the clone-then-set shape.

The recognition rule, stated precisely, is: a call to a synthesized <Clone>$ method whose result is stored in a temporary, where that temporary is subsequently mutated only through init-only setters (or direct field stores) before being used as a value. When that holds, the clone call plus the setter run collapse into a single with expression; the receiver of <Clone>$ becomes the operand before with, and each setter becomes one Member = value entry inside the braces.

What Glass reconstructs

Run it through the decompiler:

glass decompile Catalog.dll --type Catalog --member Discount
Enter fullscreen mode Exit fullscreen mode

Glass produces:

public static Product Discount(Product p, decimal newPrice)
{
    return p with
    {
        Price = newPrice,
        Stock = p.Stock - 1
    };
}
Enter fullscreen mode Exit fullscreen mode

That is the original source, down to the ordering of the initializer entries (Glass preserves the setter order from the IL, which is source order). The temporary V_0, the <Clone>$ call, and the two set_ invocations have all disappeared into the keyword — which is the honest reconstruction, because that is precisely what the C# programmer wrote.

When the pattern does not hold

The value of a structural match is that it degrades honestly. If Glass sees a <Clone>$ call whose result is mutated in some way a with block cannot express — for example a loop writing elements, a method call that is not an init setter, or branching between the clone and the stores — it does not force a with. It falls back to showing the literal clone call and the individual assignments, because inventing a with there would be a lie about the control flow. You can see this yourself by passing --no-pattern with to compare the raw lowered form against the reconstructed one:

glass decompile Catalog.dll --member Discount --no-pattern with
Enter fullscreen mode Exit fullscreen mode
public static Product Discount(Product p, decimal newPrice)
{
    Product product = p.<Clone>$();   // raw: the clone call is explicit
    product.Price = newPrice;
    product.Stock = p.Stock - 1;
    return product;
}
Enter fullscreen mode Exit fullscreen mode

Seeing both forms side by side is useful when you are auditing an unfamiliar assembly — maybe your own release build with no PDB, or a third-party library you need to interop with — and want to confirm that a method really is doing a simple copy-and-set and not something subtler hiding behind a clone.

Record structs: a different shape

One wrinkle worth knowing. A record struct has no <Clone>$ method, because value types are copied by assignment — there is nothing to call. For readonly record struct Point(int X, int Y), the with expression lowers to a copy of the struct on the stack (a ldobj/stloc of the whole value, or simply a fresh local initialized from the source) followed by the same init-setter run. Glass recognizes that shape too: a value-type copy of a record struct followed by init-only setters is the struct flavor of with, and it reconstructs the identical source with { … } syntax. The signal differs — a struct copy instead of a callvirt <Clone>$() — but the reconstruction rule is the same: copy, then overwrite named members, then use.

Why this matters for reading real code

with expressions are everywhere in modern C#: configuration objects threaded through a pipeline, state updates in a reducer, DTOs copied with one field adjusted. When you decompile such code without recognition you get a thicket of <Clone>$() temporaries and scattered setters that obscures the single intention behind each one — make a copy with these changes. Collapsing that back to with is the difference between reading someone's design and reading the compiler's bookkeeping.

Glass is a free, static-only decompiler built for exactly this kind of understanding — your own assemblies, your dependencies, your legacy builds. It reads IL to C#; it does not run, patch, or modify anything. Point it at a DLL in the Visual-Studio-native UI, the CLI, or over MCP and the with keyword comes back wherever the clone-then-set shape says it should.

Top comments (0)