tags:

views:

140

answers:

3

I have two samples of code. One works and returns the correct result, one throws a null reference exception. What's the difference? I know there's some magic happening with capturing variables for the lambda expression but I don't understand what's going on behind the scenes here.

            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();
+2  A: 

The first instance computes isXNull based on the value x had when the line bool isXNull = !x.HasValue; is executed, while the second one uses the value of x when return result2.ToList(); executes. It's not clear how you're getting a null reference exception, though, because I don't see any references.

Gabe
The null reference exception may be misleading since this code is used by LLBLGen Pro to retrieve data from the database. The value of x is not altered at any point after the initial assignment.
Mathew
+1  A: 

I'm putting this down to a peculiarity with the way LLBLGen parses LINQ queries. I created a simple framework-only test scenario which doesn't have the same problem.

Mathew
+1  A: 

Seeing that you haven't told us what data.Program is, here is some 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();
Sir Psycho