Expression trees in C# using ByRef parameters

c# expression-trees

Question

In the event that I intended to develop an expression tree that called a method having anout parameter, followed by returning theout As a consequence, how would I go about creating value?

Although it fails (throws a runtime error), the following possibly best exemplifies what I'm attempting 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'm aware that this can be resolved quite quickly in raw IL (or even without any runtime compilation), but because this is a necessary component of the expression generating process, I really hope that this isn't a restriction. After all, a full rewrite would be more than a little tedious.

1
7
12/14/2011 12:37:22 PM

Accepted Answer

For me, this works:

    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();
    }
7
12/14/2011 1:15:59 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow