Search code examples
c#lambdaasync-await

Async lambda to Expression<Func<Task>>


It is widely known that I can convert ordinary lambda expression to Expression<T>:

Func<int> foo1 = () => 0; // delegate compiles fine
Expression<Func<int>> foo2 = () => 0; // expression compiles fine

How could I do the same with async lambda? I've tried the following analogy:

Func<Task<int>> bar1 = async () => 0; // also compiles (async lambda example)
Expression<Func<Task<int>>> bar2 = async () => 0; // CS1989: Async lambda expressions cannot be converted to expression trees

Is there any workaround possible?


Solution

  • C# can only convert lambda expression to Expression tree only if code can be represented by Expression Tree, if you notice, there is no equivalent of "async" keyword in Expressions in System.Linq.Expressions

    So not only async, but anything in C# that has no equivalent expression in provided Expressions, C# can't convert it to Expression Tree.

    Other examples are

    1. lock
    2. unsafe
    3. using
    4. yield
    5. await