LINQ query: NullReferenceException

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!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: