Casting the Expression.Property result

c# expression-trees reflection

Question

How do I create a cast when creating an Expression tree dynamically?

The problem is, I have a property of type string:

public class Test
{
    public string Id { get; set; }
}

And I want to generically create a strongly typed lambda expression representing a delegate which returns an object instead of a string (Expression<Func<T, object>>).

Right now I am doing this:

private static Expression<Func<T, object>> CreateIdQuery()
{
    Type type = typeof(T);
    PropertyInfo idProperty = type.GetProperty("Id");
    ParameterExpression lambdaParam = Expression.Parameter(type, "x");
    MemberExpression body = Expression.Property(lambdaParam, idProperty);
    LambdaExpression expr = Expression.Lambda(body, lambdaParam);
    return (Expression<Func<T, object>>)expr;
}

But it throws an exception in the last line (I cannot cast Expression<Func<Test, string>> to Expression<Func<Test, object>>).

How do i cast the body of the expression (I am presuming the MemberExpression part needs to be cast into an object)?

Accepted Answer

Use Expression.Convert(body, typeof(object)).

private static Expression<Func<T, object>> CreateIdQuery()
{
    Type type = typeof(T);
    PropertyInfo idProperty = type.GetProperty("Id");
    ParameterExpression lambdaParam = Expression.Parameter(type, "x");
    MemberExpression body = Expression.Property(lambdaParam, idProperty);
    UnaryExpression converted = Expression.Convert(body, typeof(object));
    LambdaExpression expr = Expression.Lambda(converted, lambdaParam);
    return (Expression<Func<T, object>>)expr;
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why