3

I have the following expression type:

Expression<Func<MyClass, int>>

How can I convert it to a...

Expression<Func<MyClass, object>>

...and then back to a...

Expression<Func<MyClass, int>>

Byron Sommardahl
  • 12,743
  • 15
  • 74
  • 131
  • Here is a related question: http://stackoverflow.com/questions/6698553/how-do-i-translate-an-expression-tree-of-one-type-to-a-different-expression-type – agent-j Aug 01 '11 at 19:10

1 Answers1

5

I suspect you could just use Expression.Convert:

Expression<Func<MyClass, int>> original = ...;

var conversion = Expression.Lambda<Func<MyClass, object>>(
        Expression.Convert(original.Body, typeof(object)),
        original.Parameters);

var conversionBack = Expression.Lambda<Func<MyClass, int>>(
        Expression.Convert(conversion.Body, typeof(int)),
        original.Parameters);

EDIT: Okay, it looks like it works:

using System;
using System.Linq;
using System.Linq.Expressions;

class Test
{
    static void Main()
    {
        Expression<Func<string, int>> original = x => x.Length;
        var conversion = Expression.Lambda<Func<string, object>(
              Expression.Convert(original.Body, typeof(object)),
              original.Parameters);

        var conversionBack = Expression.Lambda<Func<string, int>>(
              Expression.Convert(conversion.Body, typeof(int)),
              original.Parameters);

        Console.WriteLine(conversion); // x => Convert(x.Length)
        Console.WriteLine(conversionBack); // x => Convert(Convert(x.Length))

        Console.WriteLine(conversion.Compile()("Hello")); // 5
        Console.WriteLine(conversionBack.Compile()("Hello")); // 5
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194