Why does expr1 compile but not expr2?
Func<object> func = () => new object();
Expression<Func<object>> expr1 = () => new object();
Expression<Func<object>> expr2 = func; //Cannot implicitly convert type 'System.Func<object>' to 'System.Linq.Expressions.Expression<System.Func<object>>'
A
Func<T>is a delegate (a pointer to a function), while anExpression<Func<T>>is an expression tree (a tree-like data structure that describes an operation). It follows that you cannot assign one to the other, as they are completely dissimilar.When you assign a lambda function directly to a
Func<T>the compiler compiles the code for your function and assigns a pointer to the compiled code to e.g.func.On the other hand, when you assign a lambda function directly to an
Expression<Func<T>>the compiler builds up the expression tree (which is simply an instance of a reference type) and assigns a reference to that object to e.g.expr1. This is just a convenience that the compiler provides to you, giving you a much more attractive option than manually constructing the expression tree yourself in code (which of course is also completely possible).