Question

I'm looking for the ability to convert entire methods into Expression trees. Writing it out would suck. :)

So (trivial example) given the following text:

public static int Add(int a, int b)
{
   return a + b;
}

I want to either get an in-memory object that represents this, or the following text:

ParameterExpression a = Expression.Parameter(typeof(int), "a");
ParameterExpression b = Expression.Parameter(typeof(int), "b");
var expectedExpression = Expression.Lambda<Func<int, int, int>>(
        Expression.Add(a,b),
        a,
        b
    );

Any ideas? Has anyone perhaps done something with Roslyn that can do this?

EDIT: Clarification: I want to suck in any C# method (for example, the one above) as text, and produce a resulting expression. Basically I'm looking to compile any given C# method into Expression trees.

Was it helpful?

Solution

Yes Roslyn can do, but Roslyn has its own expression tree (they are called syntax trees), Roslyn tools allow you to load and execute expressions or statements.

You will have to write your own syntax tree walker to convert Roslyn syntax tree to your expression tree, but everything may not fit correctly.

OTHER TIPS

Why not:

Expression<Func<int,int,int>> expr = (a,b) => a + b;

See billchi_ms answer at: http://social.msdn.microsoft.com/Forums/en-US/roslyn/thread/e6364fec-29c5-4f1d-95ce-796feb25a8a9

The short answer is that we may provide, or someone may write a Roslyn tree to ET v2, but Roslyn trees can represent the full languages of VB and C# while ETs v2 cannot (for example, type definitions or some ref-involved exprs).

Expression trees themselves are not generated at runtime from anything other than Expressions or lambdas (meaning your first addition statement cannot be retrieved from your executable as an expression tree). You can, however, use the code DOM on C# code (not the executable), and build a translator from the DOM to an expression tree.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top