2

The following expression lambda is fine (compiles and runs):

 Func<string, int> test = s => s?.Length ?? 0;
 Console.WriteLine(test("t")); //1

Converting it to expression tree:

System.Linq.Expressions.Expression<Func<string, int>> e = s => s?.Length ?? 0;
Console.WriteLine(e);

Generates a compile-time error:

error CS8072: An expression tree lambda may not contain a null propagating operator.

Question:

Why it is not allowed to convert the code from lambda to an expression tree?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 4
    Because it contains a null propagating operator, as the error message says. Some of the more recent features of C# are not yet supported in expression trees. – Jon Skeet Jun 28 '21 at 09:27
  • 4
    `Expressions` are stuck in the past, basically: Microsoft doesn't want to update them to support new language features. (If it did, then the authors of things like EF would also have to update those to account for the new language features) – canton7 Jun 28 '21 at 09:27
  • 1
    @JonSkeet Thanks. So it's a "not yet implemented" thing. I thought that - logically it was impossible. – Royi Namir Jun 28 '21 at 09:30
  • 1
    Well, I don't know how feasible it would be to implement without explicit support in the System.Linq.Expressions namespace. As canton7 says, it's far from simple for various reasons. – Jon Skeet Jun 28 '21 at 09:32
  • 1
    See [here](https://github.com/dotnet/csharplang/discussions/4727) and the linked issues. – canton7 Jun 28 '21 at 09:33
  • @canton7 Thanks. There is also [that link](https://github.com/dotnet/docs/issues/11321#issuecomment-473653649) - which is where this question was actually taken from – Royi Namir Jun 28 '21 at 09:34
  • More information here on SO: [Why can't I use the null propagation operator in lambda expressions?](https://stackoverflow.com/questions/28880025/why-cant-i-use-the-null-propagation-operator-in-lambda-expressions) – Andrew Morton Jun 28 '21 at 09:40

0 Answers0