tags:

views:

449

answers:

1

Hi there I basically need a function with the following signature

Expression<Func<T, object>> GetPropertyLambda(string propertyName)

I have made a few attempts but the problem arise when the property is nullable
it goes something like this

ParameterExpression param = Expression.Parameter(typeof(T), "arg");

Expression member = Expression.Property(param, propertyName);

//this next section does conver if the type is wrong however
// when we get to Expression.Lambda it throws
Type typeIfNullable = Nullable.GetUnderlyingType(member.Type);
if (typeIfNullable != null)
{
    member = Expression.Convert(member, typeIfNullable);
}        
return Expression.Lambda<Func<T, object>>(member, param);

The Exception is

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

I would really apreciate some ideas and also why this doesnt work as expected

Thanks

+4  A: 

Actually I don't think the problem has anything to do with Nullable types, but rather with value types. Try your method with a property of type decimal (not Nullable<decimal>) : it will fail the same way.

Have a look at how expression trees are generated for value and reference types (using LinqPad for instance)

  • Expression<Func<T, object>> lambda = x => x.AString; (reference type) => The body is a MemberExpression

  • Expression<Func<T, object>> lambda = x => x.ADecima;l (value type ) => The body is a UnaryExpression with NodeType = Convert and Type = typeof(object), and its Operand is a MemberExpression

I modified your method slightly to take that into account, and it seems to work fine :

ParameterExpression param = Expression.Parameter(typeof(T), "arg");

Expression member = Expression.Property(param, propertyName);

if (member.Type.IsValueType)
{
 member = Expression.Convert(member, typeof(object));
}
return Expression.Lambda<Func<T, object>>(member, param);
Thomas Levesque