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?
The error is pretty self explanatory:
It's also documented in the Async/Await FAQ.
And for good reason,
async-await
is a compiler feature on top of the framework. Expressions are used to translate code to other commands (like SQL). These other languages probably don't have anasync-await
equivalent so enabling it via expressions doesn't seem worth it.So no, I see no workaround.
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