.NET - Very strange NullReferenceException?
How can I get a NullReferenceException
in the following scenario?
Dim langs As IEnumerable(Of SomeCustomObject) = //开发者_Go百科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...
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.
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
精彩评论