The reason this happens is that Age
is a value type. In order to coerce an expression returning a value type into Func<Person,object>
the compiler needs to insert a Convert(expr, typeof(object))
, a UnaryExpression
.
For string
s and other reference types, however, there is no need to box, so a “straight” member expression is returned.
If you would like to get to the MemberExpression
inside the UnaryExpression
, you can get its operand:
private static MemberExpression GetMemberExpression<T>(
Expression<Func<T,object>> exp
) {
var member = exp.Body as MemberExpression;
var unary = exp.Body as UnaryExpression;
return member ?? (unary != null ? unary.Operand as MemberExpression : null);
}