35

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.

Joel
  • 1,033
  • 2
  • 12
  • 23

1 Answers1

44

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);
Kevin
  • 4,586
  • 23
  • 35
  • 2
    `compiledLambda.Invoke(input);` may be a better choice here if the exact type is known as @Styxxy pointed out. `Invoke` is faster than `DynamicInvoke` due to less reflection going on, see http://stackoverflow.com/questions/12858340/difference-between-invoke-and-dynamicinvoke –  May 05 '16 at 21:28