Question

I'm trying to create expressions at runtime to pass to a 3rd party API, which has a signature of Expression<Func<T, object>>. Below is what I have so far. This works fine for reference types, but value types result with an exception(3rd line).

Expression of type 'System.Boolean' cannot be used for return type 'System.Object'

I'm assuming this is due to a boxing issue, which I'm not dealing with.

I have attempted to add Expression.TypeAs(property, typeof(object)), but the API wont accept/parse this input, as it generates obj=> (obj.Foo As Object) .

Anyone have any ideas on how I can create an expression which matches the required signature for any type?

// must be in the form of 'obj => obj.Foo', or the API wont parse
private static Expression<Func<T, object>> CreatePropertyExpression(PropertyInfo propertyInfo)
{
   var instanceParam = Expression.Parameter(propertyInfo.DeclaringType, "obj");
   var property = Expression.Property(instanceParam, propertyInfo);
   var lambda = Expression.Lambda<Func<T, object>>(property, instanceParam); // kaboom

   return (Expression<Func<T, object>>)lambda;
}
Was it helpful?

Solution

Add a cast/convert:

return Expression.Lambda<Func<T, object>>(
    Expression.Convert(property, typeof(object)), instanceParam);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top