I was thinking about the difference between Expression<Func<>> and Func<>, and wondered if you could convert a static method to an expression tree as follows:
class Program
{
static void Main(string[] args)
{
Func<int, int> t = x => hrm(x);
Func<int, int> t2 = new Func<int, int>(hrm);
// Works as expected:
Expression<Func<int, int>> et = x => hrm(x);
// Brokenness:
Expression<Func<int, int>> et2 = new Func<int, int>(hrm);
}
static int hrm(int x)
{
return x + 9;
}
}
What’s so special about the second “Func<>” that it can’t be converted to an Expression, when the first one can?
I think your confusion comes from the fact that lambdas can represent expressions or delegates (with the very same syntax) in C#. So this code:
means something different depending on where it’s written. When assigned to
Func<int, int>, it’s compiled as normal to create aFunc<int, int>delegate. However, when assigned to an expression, the C# compiler defers compilation and the snippet is interpreted as an expression. Contrast this withnew Func<int, int>(hrm), which always returns aFunc<int, int>delegate.