Lambda expression to delegate instance or expression tree?

After reading this related answer -still I have a question

A lambda expression is an unnamed method written in place of a delegate instance. The compiler immediately converts the lambda expression to either:

  • A delegate instance.
  • An expression tree, of type Expression, representing the code inside the lambda expression in a traversable object model.

But When will it convert it do a delegate instance -- and when when it will convert it to expression tree ? ( didn't find related info on that one)

Not much of a related code - just tried to played with it - obviously both a matching. I didn't think so because I thought one would be a better match .

void Main()
{
     Foo( () => 0 );
}
  void Foo(Func<int > action)
{
    Console.WriteLine("1");
}

  void Foo(Expression<Func<int>> func)
{
    Console.WriteLine("2");
}

This will result in error (ambiguous between the following methods or properties)

Jon Skeet
people
quotationmark

It converts to whichever type you've asked it to. For example:

Func<int> del = () => 0; // Conversion to delegate
Expression<Func<int>> expression = () => 0; // Conversion to expression tree

In your case, you're asking the compiler to consider conversions to both forms, because of overloading. If you removed the Foo(Expression<Func<int>> func) method, the code would be valid and the compiler would convert the lambda expression to a delegate. If you removed the other method instead, the code would be valid and the compiler would convert the lambda expression to an expression tree.

people

See more on this question at Stackoverflow