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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With