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?
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.)
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