Thursday, October 25, 2012

Fixing "Not a debug ModuleBuilder." thrown by SetLocalSymInfo

This was the first problem I had when I started playing with CIL and emitting CIL code with C#'s Emit; an InvalidOperationException: Not a debug ModuleBuilder:

The reason this was happening was because of this line:

ModuleBuilder mb = ab.DefineDynamicModule(an.Name, "MainModule");

The DefineDynamicModule has an overload which lets you specify whether symbol information should be emitted, and by default it's false.

By setting this emitSymbolInfo argument to true, it will also emit the pdb file for your assembly.

So I passed in the argument and my problem was solved:
ModuleBuilder mb = ab.DefineDynamicModule(an.Name, "MainModule", true);