Not All Lambdas can be converted to expression trees!

It was surprising for me to discover that depending upon how you write your lambda syntax, it may not be able to convert to expression tree. If you are using a body expression in your lambda statements meaning you don't have an explicit return statement and no parentheses, than the lambda expression can be converted to expression tree. However lambda expression with statement body which requires an explicit return statement can only be converted to delegates. Expression trees are important because most providers of linq take expression trees and convert them to their domain specific language where as delegates gets compile into IL code which only Linq To Objects provider can understand. This is why it is important that your lambda statements are convertible to expression trees. Here is an example below which illustrates a lambda  statement that cannot be converted to expression tree and the error compiler raises in regards to that.

image

2 Comments

Comments have been disabled for this content.