Viewing the IL code that a compiled expression generates

.net-reflector c# expression-trees il


Is it possible to inspect the IL code produced when an Expression tree is called with Compile()? Take a look at this straightforward illustration:

class Program
    public int Value { get; set; }

    static void Main(string[] args)
        var param = Expression.Parameter(typeof(Program));
        var con = Expression.Constant(5);
        var prop = Expression.Property(param, typeof(Program).GetProperty("Value"));
        var assign = Expression.Assign(prop, con);
        Action<Program> lambda = Expression.Lambda<Action<Program>>(assign, param).Compile();

        Program p = new Program();

        //p.Value = 5;

The expression tree now performs the action the last line ofMain says. Open the program in Reflector after compiling it. View the IL code forp.Value = 5; it completes the task. The expression tree, however, was created and compiled during runtime. Is it possible to inspect the IL code that was generated by the compile?

1/21/2011 10:00:01 PM

Accepted Answer

Yes! Use this device:

As you might guess, this was quite helpful as I was developing and debugging Compile.

1/22/2019 9:44:19 PM

Popular Answer

Before creating a DynamicModule, DynamicType, and DynamicMethod, create a DynamicAssembly. Make that function static and public, and then provide it to the lambda's CompileTo() method. Once the assembly is complete, mark it as Save. then use the Save() function with a path argument. It'll be stored on disk. Open it in the reflector.

the following

var da = AppDomain.CurrentDomain.DefineDynamicAssembly(
    new AssemblyName("dyn"), // call it whatever you want

var dm = da.DefineDynamicModule("dyn_mod", "dyn.dll");
var dt = dm.DefineType("dyn_type");
var method = dt.DefineMethod(
    MethodAttributes.Public | MethodAttributes.Static);



Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow