views:

282

answers:

3

Hi there,

I've spent hours with this but haven't managed...

Please see example below - How can this be done?

The idea is to build a compiled expression of type Func<dynamic, dynamic> given an Expression<Func<T1,T2>> passed by the class' consumer. I have been able to solve this problem (thanks to SO) IF the types T1 and T2 are known at design time. But I'm looking for a solution for the case in which T1 and T2 are NOT known at design time.

Is this possible?

Thanks a lot!

public class ExpressionExample
{
    private Func<dynamic, dynamic> _compiledExpression;

    public ExpressionExample(LambdaExpression lambdaExpression)
    {
        // How does one get a compiled expression of type
        // Func<dynamic, dynamic> at this point given lambdaExpression?
    }
}
A: 

You'll need to call Compile on the LambdaExpression, then build and compile another expression tree that calls the delegate using Expression.Invoke(Expression, params Expression).

SLaks
The problem is the second tree needs to include type conversions, otherwise the call to the delegate fails; I don't know the types at design time and the compiler tells me that it can not "infer those from usage"...
d.
You need to build the tree at runtime. You might also need to call `Expression.Convert`.
SLaks
+1  A: 

Unless I'm not understanding your question, this should work:

public class ExpressionExample<T1, T2>
{
    private Func<dynamic, dynamic> _compiledExpression;

    public ExpressionExample(
        Expression<Func<T1, T2>> lambdaExpression)
    {
        // How does one get a compiled expression of type
        // Func<dynamic, dynamic> at this point given lambdaExpression?
        var func = lambdaExpression.Compile();
        _compiledExpression = (dynamic x) => (dynamic)func((T1)x);
    }
}
Jacob
I assume that he doesn't want to change the function's signature. If he can, this is the best solution.
SLaks
Hi guys, this is exactly what I was looking for! Thanks a lot, I really appreciate it. I can't believe I spent so much time with this to not even come close to the solution. But well, I learnt quite a lot along the way too.
d.
No problem. Don't forget to mark my answer as accepted :)
Jacob
A: 

I was looking in to something similar myself. Being a newbie I won't attempt to answer your question in full but maybe you can find the answer from the answer given to me from forums.asp.net which I also posted right here on stackoverflow.

Martin