If I wanted to create an expression tree that called a method with an out
parameter and then returned the out
value as a result.. how would I go about it?
The following does not work (throws a runtime exception), but perhaps best demonstrates what I'm trying to do:
private delegate void MyDelegate(out int value);
private static Func<int> Wrap(MyDelegate dele)
{
MethodInfo fn = dele.Method;
ParameterExpression result = ParameterExpression.Variable(typeof(int));
BlockExpression block = BlockExpression.Block(
typeof(int), // block result
Expression.Call(fn, result), // hopefully result is coerced to a reference
result); // return the variable
return Expression.Lambda<Func<int>>(block).Compile();
}
private static void TestFunction(out int value)
{
value = 1;
}
private static void Test()
{
Debug.Assert(Wrap(TestFunction)() == 1);
}
I know this can be fairly easily solved in raw IL (or indeed without runtime compilation at all), but unfortunately this is part of a much larger expression building process... so I'm really hoping this isn't a limitation, as a complete rewrite would be more than a bit of a pain.
This works for me:
private static Func<int> Wrap(MyDelegate dele)
{
var fn = dele.Method;
var result = ParameterExpression.Variable(typeof(int));
var block = BlockExpression.Block(
typeof(int),
new[] { result },
new Expression[]
{
Expression.Call(fn, result),
result,
});
return Expression.Lambda<Func<int>>(block).Compile();
}
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