17

I don't understand what is happening here:

Both of these lines compile:

 Func<object> func = () => new object();

 Expression<Func<object>> expression = ()=>new object();

But this doesn't:

 expression = func;

There isn't an implicit operator on LambdaExpression or Expression<TDelegate> that converts a delegate to the expression, so something else must be happening to make the assignment work. What is it?

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
smartcaveman
  • 41,281
  • 29
  • 127
  • 212

1 Answers1

30

It's not an implicit conversion in the usual sense - it's a compiler trick. The compiler detects which one is expected from the context, and then compiles it either as a delegate (a hidden method on your class) or as an expression (a chunk of code that constructs the expression by calling the methods on System.Linq.Expressions.Expression).

This is the reason you can't directly assign a lambda expression to a variable of type object or var, among other things, because the compiler has to be able to know whether you mean a delegate or an expression.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • 1
    More [here](http://msdn.microsoft.com/en-us/library/bb308966.aspx#csharp3.0overview_topic20). – Kirk Woll May 02 '11 at 20:49
  • 5
    Re the last - plus it would need to decide *what delegate type* (or expression-of-delegate-type) to use; there is nothing special about `Func<...>` etc. – Marc Gravell May 02 '11 at 21:06