Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 used.

The following code throws a compile error that we can't use null propagating operator in lambda.

var cnt = humans.AsQueryable().Count(a => a.House?[0].Price == 5000);

The error :

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

C# Could easily translate above code to the code to following code if really can't do anything else!

var cnt = humans.AsQueryable().Count(a => a.House != null && a.House[0].Price == 5000);

I'm curious why C# does nothing and simply throws a compiler error?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
451 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...