Execute LambdaExpression and get returned value as object
Asked Answered
V

1

36

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.

Valarievalda answered 31/7, 2013 at 21:56 Comment(5)
Why not just var func = new Func<int, string>(x => { return string.Format("My int = {0}", x); });?Basie
@PoweredByOrange I'm assuming the question is simplified.Conglomeration
@Conglomeration Makes sense, otherwise a simple string.Format() would do it :)Basie
Why do you want to use late binding (DynamicInvoke). If it is possible, I would try to avoid this (because you have no compile time check; thus it is very much possible you get runtime errors).Tenuis
@Tenuis excellent point! I've updated my answer accordingly.Conglomeration
C
45

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);
Conglomeration answered 31/7, 2013 at 22:1 Comment(1)
compiledLambda.Invoke(input); may be a better choice here if the exact type is known as @Tenuis pointed out. Invoke is faster than DynamicInvoke due to less reflection going on, see #12858840Kathie

© 2022 - 2024 — McMap. All rights reserved.