Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute LambdaExpression and get returned value as object

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.

like image 983
Joel Avatar asked Jul 31 '13 21:07

Joel


1 Answers

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); 
like image 55
Kevin Avatar answered Oct 06 '22 00:10

Kevin