How to specify return type of expression tree?

c# expression-trees lambda


The run-time seems to choose the return type automatically if I manually construct an expression tree. Therefore, if I construct an expression tree that like this:

// Order contains a navigation property for Customer
(Order o) => o.Customer;

The run-time chooses Customer as the return type, which means basically this:

Expression<Func<Order, Customer>> efd = (Order o) => o.Customer;

How can I construct it—or alter what I have constructed—so that the return is an object, as in the expression:

Expression<Func<Order, object>> ef = (Order o) => o.Customer;

Since this is generic, I was unaware that the return type would be Customer at the time of compilation; it could have been any navigation property from (in this example, order).


Let's suppose I begin with the following phrase:

Expression<Func<OrderDTO, object>> ef = (OrderDTO o) => o.Customer;

I have a procedure that rebuilds this while switching the kind ofOrderDTO to Order by moving through the tree and altering the kinds in accordance with a map of from/to types. I'm just doing that, but the expression that comes out is

Expression<Func<Order, Customer>> ef = (Order o) => o.Customer;

As a result, when I rebuild the tree, I must somehow indicate the return type since I didn't define it, but it seems that the system is doing it automatically. Thanks, Ray

1/14/2013 7:29:04 PM

Popular Answer

Without actually viewing your code, it's difficult to determine, however it seems like you're using one of the Expression.Lambda() versions that forbids you from specifying the type of the produced expression. You are correct that if you do so, the kind of delegate will be chosen at random.

You may either use an updated version ofExpression.Lambda() that allows you to use a type argument to indicate the delegate type (for example,Expression.Lambda<Func<Order, object>>(…) ), or, in your instance, more likely, the variant where the delegate type is supplied as a regular argument of typeType (Expression.Lambda(funcType, …) ).

1/14/2013 7:51:02 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow