tags:

views:

628

answers:

1

Hi guys,

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 ;)

+6  A: 

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");
        Console.WriteLine(dt);
    }        
}
Jon Skeet
Beat me to it...
Marc Gravell
Fantastic!! Many Thanks!
antonioh
I was pretty surprised to, given our relative expertise in these matters :) At first I forgot to use "expression.Body" and ended up getting a Func back...
Jon Skeet
I glance away from SO for a few minutes from time to time ;-p
Marc Gravell