Archive for the ‘LINQ’ Category

LINQ query: NullReferenceException

September 23, 2009

Code example:

1    Dim queryResult = customers.Where(Function (cu)
2    If queryResult.Count>0 Then
3        End Sub
4    End If
5    …something

The line 1 runs OK, the lne 2 calls NullReferenceException!
You can think, because queryResult is empty? False!
queryResult was evaluated only at line 2, as the results are used.
It is “Deferred Evaluation” of LINQ.
And during the evaluation a Null Reference was found. For example, customer.Type is Nothing!

Think of it: the LINQ query will be evaluated, if it will be used, not before!

If you use the results in function .ToList():

1    Dim queryResult as List(Of customer) = customers.Where(Function (cu)

then NullReferenceException will be called immediately in line 1, because the LINQ will be evaluated in the same code line, but only for function .ToList(), not in the LINQ expression itself!