How to debug dynamically generated method?

.net, debugging, dynamic, il, visual-studio-2012

Solution

You need to mark the generated code as debuggable. Something like:

Type daType = typeof(DebuggableAttribute);
ConstructorInfo ctorInfo = daType.GetConstructor(new Type[] { typeof(DebuggableAttribute.DebuggingModes) });
CustomAttributeBuilder caBuilder = new CustomAttributeBuilder(ctorInfo, new object[] { 
  DebuggableAttribute.DebuggingModes.DisableOptimizations | 
  DebuggableAttribute.DebuggingModes.Default
});
assembly.SetCustomAttribute(caBuilder);

You also should add a sourcefile:

ISymbolDocumentWriter doc = module.DefineDocument(@"SourceCode.txt", Guid.Empty, Guid.Empty, Guid.Empty);

You should now be able to step into the dynamically generated method.

Problem

I have a dynamically created assembly, a module, a class and a dynamically generated method. ``` AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(...); ModuleBuilder module = assembly.DefineDynamicModule(...); TypeBuilder tb = module.DefineType(...); MethodBuilder mb = tb.DefineMethod(...); ILGenerator gen = mb.GetILGenerator(); ``` How can I debug method code generated with `ILGenerator`? I use Visual Studio 2012 debugger, but it just steps through a method call.

Original source