What does Lambda Expression Compile() method do?

jk_ picture jk_ · Nov 14, 2011 · Viewed 19.9k times · Source

I am trying to understand AST in C#. I wonder, what exactly Compile() method from this example does.

// Some code skipped    
Expression<Func<string, int, int, string>> data = Expression.Lambda<Func<string, int, int, string>>( 
        Expression.Call(s, typeof(string).GetMethod(“Substring”, new Type[] { typeof(int), typeof(int) }), a, b), 
        s, a, b 
    ); 
Func<string, int, int, string> fun = data.Compile(); 

To prevent misunderstandings, I understand the Expression.Lambda and Expression.Call constructs. What interests me is the Compile() method. Does it somehow produce real MSIL? Can I see the MSIL?

Answer

Eric Lippert picture Eric Lippert · Nov 14, 2011

What interests me is the Compile() method. Does it somehow produce real MSIL?

Yes. The Compile method runs a visitor over the lambda body block and generates IL dynamically for each subexpression.

If you're interested in learning how to spit IL yourself, see this "Hello World" example of how to use Lightweight Codegen. (I note that if you are in the unfortunate position of having to use Lightweight Codegen in a partially trusted appdomain then things can get a bit weird in a world with Restricted Skip Visibility; see Shawn Farkas's article on the subject if that interests you.)

Can I see the MSIL?

Yes, but you need a special "visualizer". The visualizer I used to debug Compile() while I was implementing my portions of it can be downloaded here:

http://blogs.msdn.com/b/haibo_luo/archive/2005/10/25/484861.aspx