Why can't I use the null propagation operator in lambda expressions?

后端 未结 1 1415
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 21:28

I often use null propagating operator in my code because it gives me more readable code, specially in long queries I don\'t have to null-check every single class that is use

相关标签:
1条回答
  • 2020-12-02 22:24

    It's complicated since expression tree lambdas (unlike delegate lambdas) are interpreted by already existing LINQ providers which don't yet support null propagating.

    Converting to a conditional expression is not always accurate as there are multiple evaluations while with ?. there's only a single evaluation for example:

    customer.Where(a => c.Increment()?.Name) // Written by the user 
    customer.Where(a => c.Increment() == null ? null : c.Increment().Name) // Incorrectly interpreted by an old LINQ provider
    

    You can go deeper in the relevant discussion on CodePlex where 3 solutions are offered: NullPropagationExpression, ConditionalExpression & a hybrid

    0 讨论(0)
提交回复
热议问题