views:

66

answers:

1

Hi

I have the following code

Expression<Func<IPersistentAttributeInfo, bool>> expression = info => info.Owner== null;

and want to tranform it to

Expression<Func<PersistentAttributeInfo, bool>> expression = info => info.Owner== null;

PersistentAttributeInfo is only known at runtime though

Is it possible?

+2  A: 

If PersistentAttributeInfo is only known at runtime, you obviously cannot write the lambda statically and have the compiler do the heavy lifting for you. You'll have to create a new one from scratch:

Type persistentAttributeInfoType = [TypeYouKnowAtRuntime];
ParameterExpression parameter = Expression.Parameter(persistentAttributeInfoType, "info");
LambdaExpression lambda = Expression.Lambda(
    typeof(Func<,>).MakeGenericType(persistentAttributeInfoType, typeof(bool)), 
    Expression.Equal(Expression.Property(parameter, "Owner"), Expression.Constant(null)),
    parameter);

You can invoke lambda.Compile() to return a Delegate that is analogous to the transformed lambda expression in your example (though of course untyped).

Kirk Woll
Impressive work... I played with it for about 20 minutes and gave up...
James Curran