Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've created an expression that I'm using for sorting which works fine, until I hit a DateTime field, where I get the following error (on the second line):

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

Here's my code:

ParameterExpression param = Expression.Parameter(typeof(MyEntity), "x");

Expression<Func<MyEntity, object>> sortExpression =
    Expression.Lambda<Func<AMyEntity, object>>(
        Expression.Property(param, sortKey), param);

Can anyone help at all?

like image 742
Wildcat Avatar asked Jan 23 '12 16:01

Wildcat


2 Answers

Just add a conversion in there:

Expression<Func<MyEntity, object>> sortExpression =
    Expression.Lambda<Func<AMyEntity, object>>(
        Expression.Convert(
            Expression.Property(param, sortKey),
            typeof(object)),
        param);
like image 62
Jon Skeet Avatar answered Oct 11 '22 19:10

Jon Skeet


You appear to be expecting auto-boxing of value-types to match the return-type of the expression. Unfortunately, Expression.Lambda does not do this.

You can use Expression.Convert to perform the boxing.

var body = Expression.Convert(Expression.Property(param, sortKey), typeof(object));
var sortExpression = Expression.Lambda<Func<AMyEntity, object>>(body, param);

If for some reason you don't want the conversion operation to be present in the expression if the property is already a reference-type, you can branch as required:

Expression body = Expression.Property(param, sortKey);

if(body.Type.IsValueType)
   body = Expression.Convert(body, typeof(object));
like image 27
Ani Avatar answered Oct 11 '22 18:10

Ani