Execute LambdaExpression and get returned value as object

Joel picture Joel · Jul 31, 2013 · Viewed 12.6k times · Source

Is there a clean way to do this?

Expression<Func<int, string>> exTyped = i => "My int = " + i;
LambdaExpression lambda = exTyped;

//later on:

object input = 4;
object result = ExecuteLambdaSomeHow(lambda, input);
//result should be "My int = 4"

This should work for different types.

Answer

Kevin picture Kevin · Aug 1, 2013

Sure... you just need to compile your lambda and then invoke it...

object input = 4;
var compiledLambda = lambda.Compile();
var result = compiledLambda.DynamicInvoke(input);

Styxxy brings up an excellent point... You would be better served by letting the compiler help you out. Note with a compiled expression as in the code below input and result are both strongly typed.

var input = 4;
var compiledExpression = exTyped.Compile();
var result = compiledExpression(input);