# Obfuscating code that generates code at runtime


Serializers, ORMs, DI containers, mappers, and rule engines all do the same trick under the hood: they write IL at runtime instead of calling your methods directly, because a generated, specialised method is far faster than reflection on every call. .NET gives you three main ways to do it — `DynamicMethod` + `ILGenerator`, `TypeBuilder` via `Reflection.Emit`, and `Expression.Compile` over LINQ expression trees. All three interact with obfuscation in a way the compiler cannot warn you about, because the breakage happens at runtime, in code that did not exist at build time. Here is the precise model of what is safe and what is not.

## The key distinction: the generator ships, the generated code does not

Two different pieces of code are in play, and conflating them is where the confusion starts.

The **generated code** — the `DynamicMethod` body, the `TypeBuilder` type, the compiled expression delegate — is created in memory at runtime and never written to your assembly. The obfuscator never sees it, so it is neither protected nor harmed. (If protecting it mattered you could not, anyway; it is ephemeral.)

The **generator** — the method full of `il.Emit(...)` calls, or the expression-building code — *is* in your assembly. It is plain IL and gets renamed, control-flow-flattened, and string-encrypted like everything else. That is fine, with one catch: the generator usually references *your* types and members, and how it references them decides whether obfuscation breaks it.

<svg viewBox="0 0 740 200" role="img" aria-labelledby="emit-title" xmlns="http://www.w3.org/2000/svg" style="max-width:100%;height:auto;font-family:system-ui,sans-serif">
  <title id="emit-title">The generator is obfuscated; the generated code is runtime-only</title>
  <style>
    .b{fill:none;stroke:#64748b;stroke-width:1.5}.t{fill:currentColor;font-size:13px}.s{fill:#64748b;font-size:11px}
    .ob{stroke:#6366f1;stroke-width:2}.ar{stroke:#64748b;stroke-width:1.5;marker-end:url(#e)}
  </style>
  <defs><marker id="e" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0L10 5L0 10z" fill="#64748b"/></marker></defs>
  <text class="s" x="20" y="36">In your assembly (obfuscated):</text>
  <rect class="b ob" x="20" y="46" width="300" height="50" rx="8"/>
  <text class="t" x="34" y="68">Generator method</text><text class="s" x="34" y="86">ILGenerator.Emit / Expression tree</text>
  <line class="ar" x1="320" y1="71" x2="430" y2="71"/>
  <text class="s" x="330" y="64">emits at runtime</text>
  <text class="s" x="450" y="36">Runtime-only (never on disk):</text>
  <rect class="b" x="450" y="46" width="270" height="50" rx="8"/>
  <text class="t" x="464" y="68">DynamicMethod body</text><text class="s" x="464" y="86">discarded at process exit</text>
  <text class="s" x="20" y="150">Risk is only in the arrows the generator uses to name YOUR members:</text>
  <text class="s" x="20" y="170">string lookup → breaks on rename · typeof/MethodInfo token → survives (rewritten with the rename).</text>
</svg>

## Where it breaks: string-based member lookup

A generator that resolves the members it emits calls to by **string name** is the one that breaks. Consider a `DynamicMethod` that calls a getter it found by name:

```csharp
MethodInfo getter = typeof(Order).GetMethod("get_Total")!; // string lookup
var dm = new DynamicMethod("ReadTotal", typeof(decimal), new[] { typeof(Order) });
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, getter);   // emits a call to whatever `getter` resolved to
il.Emit(OpCodes.Ret);
```

After obfuscation renames `Order.Total` (and its `get_Total` accessor), the string `"get_Total"` no longer matches anything, so `GetMethod` returns null and the next line throws `NullReferenceException` / `ArgumentNullException` — at runtime, with no compile-time hint. Same failure for `TypeBuilder` code that defines overrides by name, and for `Expression.Property(p, "Total")`.

The fix is one of two things. **Keep the name** of the specific members the generator looks up by string (a targeted [keep-rule](https://delta1labs.com/blog/nebula-keep-list-rename-exclusions/), not a blanket exclusion). Or, better, **stop using strings**: capture the member through something the obfuscator can rewrite.

## What survives: references the obfuscator can see

When the generator captures a member as a *metadata reference* rather than a string, the obfuscator rewrites that reference as part of the rename, and everything keeps working:

```csharp
// Survives renaming — MethodInfo captured from a delegate, not a string.
MethodInfo getter = ((Func<Order, decimal>)(o => o.Total)).Method; // won't help: that's a lambda's Method
// Better: read the MemberInfo out of an expression tree
Expression<Func<Order, decimal>> e = o => o.Total;
var prop = (PropertyInfo)((MemberExpression)e.Body).Member;          // real PropertyInfo, token-based
```

Compiled **expression trees** are the friendly case: `o => o.Total` carries a `PropertyInfo` reference that the obfuscator renames along with the property, so `Expression.Compile()` binds to the right member afterwards. The rule of thumb: *expression trees and `typeof(T).GetMethod(someMethodInfo-derived-reference)` are rewrite-safe; any `"string"` member name in a generator is not.*

## A practical checklist

- Audit your runtime-codegen sites for **string literals naming your own members**; those are the breakage points.
- Prefer expression trees or delegate/`MethodInfo` capture over `GetMethod("Name")` where you can.
- For the unavoidable string lookups, add **targeted keep-rules** for exactly those members — and remember their *bodies* are still obfuscated; only the name survives.
- Test the obfuscated build's codegen paths explicitly, because the compiler and even a smoke test that skips the generated path will not catch a broken emit.

## Doing this with Nebula

[Nebula](https://delta1labs.com/nebula) renames, flattens, and string-encrypts your generators like any other code, and its [keep-rule](https://delta1labs.com/blog/nebula-keep-list-rename-exclusions/) model is precise enough to preserve exactly the members your `Reflection.Emit` or expression-building code resolves by name, while still obfuscating their bodies. Pair it with the guidance in [reflection and serialization pitfalls](https://delta1labs.com/blog/obfuscation-reflection-serialization-pitfalls/) and you can ship obfuscated code that generates code without a single runtime surprise.

Start with the [free edition](https://delta1labs.com/blog/free-dotnet-obfuscator/), or see the [plans](https://delta1labs.com/pricing?product=nebula).

