Search code examples
c#.netvisual-studio-2010codedom

Is it possible to debug code compiled at runtime?


I have a need to compile some code using CodeDomProvider.CompileAssemblyFromSource. How would one go about debugging it? Basically, I want to compile it, create instance of a type and then step into the code for the type.


Solution

  • After I posted a question, I realized that my problem was that I was generating the assembly from string, not from file. I went back and changed the code to run with different options when in DEBUG and I am able to step right in from unit test code. Also one has to set GenerateInMemory to false and IncludeDebugInformation to true.

    #if DEBUG
                @params.IncludeDebugInformation = compilationContext.IncludeDebugInformation;
                @params.GenerateInMemory = compilationContext.GenerateInMemory;
                var fileName = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,@"..\..\" + compilationContext.AssemblyOutputName + ".cs"));
                File.WriteAllText(fileName,compilationContext.StringToCompile);
                return _codeDomProvider.CompileAssemblyFromFile(@params,fileName);
    #else
                return _codeDomProvider.CompileAssemblyFromSource(@params, compilationContext.StringToCompile);
    #endif