antonioh antonioh - 2 months ago 7x
C# Question

How to cast Expression<Func<T, DateTime>> to Expression<Func<T, object>>

I've been searching but I can't find how to cast from the type

Expression<Func<T, DateTime>>

to the type:

Expression<Func<T, object>>

So I must turn again to the SO vast knowledge ;)


You can't just cast between them, as they're not the same kind of thing. However, you can effectively add a conversion within the expression tree:

using System;
using System.Linq.Expressions;

class Test
    // This is the method you want, I think
    static Expression<Func<TInput,object>> AddBox<TInput, TOutput>
        (Expression<Func<TInput, TOutput>> expression)
        // Add the boxing operation, but get a weakly typed expression
        Expression converted = Expression.Convert
             (expression.Body, typeof(object));
        // Use Expression.Lambda to get back to strong typing
        return Expression.Lambda<Func<TInput,object>>
             (converted, expression.Parameters);

    // Just a simple demo
    static void Main()
        Expression<Func<string, DateTime>> x = text => DateTime.Now;
        var y = AddBox(x);        
        object dt = y.Compile()("hi");