Search code examples
c#lambdaexpression-trees

Getting the result from an Expression


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.


Solution

  • 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();
        }
    }