Getting the result from an Expression

c# expression-trees lambda

Question

I've created a lambda expression at runtime, and want to evaluate it - how do I do that? I just want to run the expression by itself, not against any collection or other values.

At this stage, once it's created, I can see that it is of type Expression<Func<bool>>, with a value of {() => "MyValue".StartsWith("MyV")}.

I thought at that point I could just call var result = Expression.Invoke(expr, null); against it, and I'd have my boolean result. But that just returns an InvocationExpression, which in the debugger looks like {Invoke(() => "MyValue".StartsWith("MyV"))}.

I'm pretty sure I'm close, but can't figure out how to get my result!

Thanks.

Accepted Answer

Try compiling the expression with the Compile method then invoking the delegate that is returned:

using System;
using System.Linq.Expressions;

class Example
{
    static void Main()
    {
        Expression<Func<Boolean>> expression 
                = () => "MyValue".StartsWith("MyV");
        Func<Boolean> func = expression.Compile();
        Boolean result = func();
    }
}

Popular Answer

As Andrew mentioned, you have to compile an Expression before you can execute it. The other option is to not use an Expression at all, which woul dlook like this:

Func<Boolean> MyLambda = () => "MyValue".StartsWith("MyV");
var Result = MyLambda();

In this example, the lambda expression is compiled when you build your project, instead of being transformed into an expression tree. If you are not dynamically manipulating expression trees or using a library that uses expression trees (Linq to Sql, Linq to Entities, etc), then it can make more sense to do it this way.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why