tags:

views:

526

answers:

2

I have a function that has the following signature...

public string DoJunk(Expression<Func<bool>> expression)

I'm trying to find a way to convert the "expression" parameter back to something resembling the original source code (or at least a c# representation of the original souce code). So, if someone calls the function like this...

DoJunk(() => (i + j) * 9 == Math.Round((double)j / (i - 3), 4))

...I'd like to be able to convert the expression to this...

(i + j) * 9 == Math.Round((double)j / (i - 3), 4)

Has anyone done this?

+3  A: 

Here's an interesting article, with code, discussing the conversion of expression trees back into something that resembles (roughly) the original source:

Expression Trees-Lambdas to CodeDom Conversion

As a side-note, have you tried calling the expression's ToString method?

Expression<Func<int, int, bool>> expr =
    (i, j) => (i + j) * 9 == Math.Round((double)j / (i - 3), 4);

Console.WriteLine(expr.ToString());
// (i, j) => (Convert(((i + j) * 9)) = Round((Convert(j) / Convert((i - 3))), 4))

Console.WriteLine(expr.Body.ToString());
// (Convert(((i + j) * 9)) = Round((Convert(j) / Convert((i - 3))), 4))
LukeH
I have tried using ToString(), but it gives me something pretty nasty looking...(Convert(((value(LambdaToStringSpike.Program+<>c__DisplayClass0).i + value(LambdaToStringSpike.Program+<>c__DisplayClass0).j) * 9)) = Round((Convert(value(LambdaToStringSpike.Program+<>c__DisplayClass0).j) / Convert((value(LambdaToStringSpike.Program+<>c__DisplayClass0).i - 3))), 4))
herbrandson
Yep, I think the output you're seeing is what's generated behind-the-scenes by the C# compiler to handle the captured variables `i` and `j`. In my examples, `i` and `j` are locals, so the output is much closer to the original source code.
LukeH
+2  A: 

Personally I thought I had a need to do somethig similar to what you are wanting to do, but found a much simpler solution. One of the books I found quite useful when I was going through the exercise was Programming Linq. There is a chapter in that book called Advanced Linq, which gives you all the arsenal you would need to accomplish what you are wanting to accomplish. You can read parts of this chapter on Inside Expression Trees on-line through the Amazon.com web site. The link is here. One thing to keep in mind is is the transformation or the interpetation of an expression tree what you really need.

Michael Mann