Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ByRef parameters with Expression trees in C#

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.

like image 301
Mania Avatar asked Dec 14 '11 12:12

Mania


1 Answers

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();
    }
like image 198
max Avatar answered Sep 29 '22 23:09

max