4

As I understand it, I can use this:

Func<string> f1 = () => DateTime.Now.ToString();

as a shorthand for:

Func<string> f2 = () => { return DateTime.Now.ToString(); };

My question is why can't I do the same with expressions:

Expression<Func<string>> exp1 = () => DateTime.Now.ToString();
Expression<Func<string>> exp2 = () => { return DateTime.Now.ToString(); };

The second line does not compile.

j0aqu1n
  • 1,013
  • 7
  • 14
  • You can't convert this particular type lambda (posessing a statement body i.e. the curly braces) to an expression tree. You can't use anonymous methods either – Charleh Mar 20 '13 at 14:27
  • I think the error message from the compilker says it all: "A lambda expression with a statement body cannot be converted to an expression tree". As for why not: As Eric Lipeprt is frequently caught saying, all featrures are originally unimplmented, until they are implemented as the result of the Language team deciding the benefit of implementing them exceeds the cost of doing so. – Pieter Geerkens Mar 20 '13 at 14:28
  • in the second case the compiler will generate code to build an expression tree that represents the lambda expression. It is not the same as your first scenario – NoviceProgrammer Mar 20 '13 at 14:30

2 Answers2

3

The compiler handles with these to objects in different manner. The first one will compile to an IL method that gets nothing and returns DateTime.Now.ToString(). The compiler itself skips the return and makes it as

string myMethod() { return DateTime.Now.ToString(); }

The second one is genereted into LinqExpression object, which handles it in another way, so that such syntax causes error. While they look the same first time, the compiler generates different code for them.

You can read Why would you use Expression<Func<T>> rather than Func<T>? about the differences between these two structures

Community
  • 1
  • 1
Alex
  • 8,827
  • 3
  • 42
  • 58
1

Expressions<>s cant be generated for statements, only expressions. The moment you put braces around an expression it becomes a statement/compound-statement.

Sean
  • 60,939
  • 11
  • 97
  • 136