d..
d..

Reputation: 1103

More on casting Func<T,T> and Expression<Func<T,T>>

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?
    }
}

Upvotes: 2

Views: 1013

Answers (3)

Martin
Martin

Reputation: 2971

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.

Upvotes: 0

Jacob
Jacob

Reputation: 78910

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);
    }
}

Upvotes: 1

SLaks
SLaks

Reputation: 888117

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).

Upvotes: 0

Related Questions