Lambda expression to delegate instance or expression tree?

After reading this related answer, if I have a question

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

  • Delegate Instance.
  • An expression tree of type Expression that represents the code inside a lambda expression in a passing object model.

But when does he convert it to a delegate instance, and when does he convert it to an expression tree? (did not find relevant information about this)

Not much related code - just tried to play with it - obviously a coincidence. I didn’t think so, because I thought it would be better to 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 an error (ambiguously between the following methods or properties)

+4
1

, . :

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

- . Foo(Expression<Func<int>> func), , . , , - .

+5

Source: https://habr.com/ru/post/1537682/


All Articles