Lambda expressions and nullable types

I have two code samples. One works and returns the correct result, one chose the null reference exception. What's the difference? I know that some kind of magic happens with capturing variables to express lambda, but I don’t understand what is going on behind the scenes.

int? x = null; bool isXNull = !x.HasValue; // this works var result = from p in data.Program where (isXNull) select p; return result.Tolist(); // this doesn't var result2 = from p in data.Program where (!x.HasValue) select p; return result2.ToList(); 
+4
source share
3 answers

I attribute this to the fact that LLBLGen parses LINQ queries. I created a simple test case that does not have the same problem.

+1
source

The first instance evaluates isXNull based on x when the line bool isXNull = !x.HasValue; and the second uses the value of x when return result2.ToList(); . However, it is unclear how you get the reference link exception, because I do not see the links.

+2
source

Seeing that you didn’t tell us what data.Program is, here is the code that I tried and it worked ... in LINQPad.

 var Program = new [] {"asd","asd"}; int? x = null; bool isXNull = !x.HasValue; // this works var result = from p in Program where (isXNull) select p; // this doesn't var result2 = from p in Program where (!x.HasValue) select p; result.Dump(); result2.Dump(); 
+1
source

Source: https://habr.com/ru/post/1311374/


All Articles