0

I have method that looks something like

ISomething<U> Foo<T, U>(Expression<Func<T, U>> selector)
{
    Expression<Func<T, object>> generalSelector =
         ChangeSelectorReturnType<object>(selector);
    Use(generalSelector);
    return new Something<U>(selector);
}

What is the simplest code to implement ChangeSelectorReturnType assuming selector will always be a simple property accessor such as x => x.Property?

I know the solution presented in another question works, but it requires a full expression visitor because no assumptions are made. I'm ok with assumptions in this case.

Community
  • 1
  • 1
Kit
  • 20,354
  • 4
  • 60
  • 103
  • I think that the code accompanying this question is over-sanitized. Where is the generic specified? – Chris Shain Jan 09 '12 at 18:45
  • Oh. It was actually on a containing interface, but I'll add it to the method just for clarity. – Kit Jan 09 '12 at 19:00

1 Answers1

0

Use the Convert() expression on the body of the lambda. That will allow you to change its type. Then recreate the lambda.

var modifiedBody = Expression.Convert(selector.Body, typeof(object));
var generalSelector =
    Expression.Lambda<Func<T, object>>(modifiedBody, selector.Parameters);
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272