views:

106

answers:

3

How can I get a NullReferenceException in the following scenario?

 Dim langs As IEnumerable(Of SomeCustomObject) = //some LINQ query
 If langs Is Nothing Then Return Nothing 
 If langs.Count = 1 Then //NullReferenceException here

What am I missing here? Debug shows that langs is really just a LINQ queryresult without any results...

+7  A: 

The exception is probably coming from the evaluation of your LINQ query. LINQ queries are evaluated in a lazy fashion: that is, no code is actually executed until you actually use the value.

For example, if you have the following (I don't know the LINQ syntax for VB, so this is C# but the same thing applies):

string str = null;
IEnumerable<char> chs = from ch in str select ch;
if (chs.Count() == 0) // NullReferenceException here

Also, you will never get a null returned from the creation of the LINQ query so your If langs Is Nothing check is not needed.

Dean Harding
Nope, all parameters in the query have values...
Ropstah
@ropstah: Can you post the actual LINQ query and the stack trace then?
Dean Harding
I did actually, and there was something horribly wrong. An entire object was missing in the query, so you were totally right in your answer!
Ropstah
A: 

Because you're using IEnumerable instead of ICollection. In order to have the IEnumerable return a count, you would need to implement something that calls GetEnumerator (which is likely where the NullReferenceException is occurring). ICollection applies this logic automagically.

Joel Etherton
I believe in this case, the code is using the `Count` extension method (VB makes the fact that it's a method call hard to figure out...)
Dean Harding
A: 

Because langs won't be evaluated until it is accessed, you can force the evaluation by converting to a list:

 Dim langs As IEnumerable(Of SomeCustomObject) = //some LINQ query 
 Dim langsList as List(Of SomeCustomObject) = langs.ToList()
 If langsList Is Nothing Then Return Nothing  
 If langsList.Count = 1 Then //NullReferenceException here 
Paul Kearney - pk
This doesn't work obviously, because the `NullReferenceException` moves to the second line where `langs.ToList()` is called.
Ropstah
@ropstah, can you put the actual code up? If langs is a LINQ query result, it shouldn't evaluate to null when doing .ToList(). Worse case you'd end up with an empty list.
Paul Kearney - pk