C# expressions syntax shorthand

c#, delegates, lambda

Solution

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

Problem

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.

Original source

Related problems