We had a Nullable object must have a value
error today on this line of code:
list = From x In Me Where x.FooDate.HasValue AndAlso x.FooDate.Value.Date >= barDate
Funny thing is that I feel sure this used to work fine (and there has always been a sprinkling of null values in the underlying data). And logically it looks fine to me. The check for HasValue
and the AndAlso
look as if they're going to shield us from any Null danger.
But it seems suddenly they're not. Am I missing something?
OK, we can correct it to this, which eliminates the error:
list = From x In Me Where If(x.FooDate.HasValue, x.FooDate.Value.Date >= barDate,False)
But this looks to me less readable. Any thoughts?
Update ... and Confession:
In simplifying the above code to shorten the line I left out a crucial chunk of the code. The original problem should have read something like:
list = From x In Me Where x.FooDate.HasValue AndAlso x.FooDate.Value.Date >= fromDate And x.FooDate.Value.Date <= toDate
Because of the rules of shortcircuiting and operator precedence (as outlined in an answer to a long ago question of my own) I needed to add brackets round the second part of the instruction in order to stop LINQ evaluating the second x.FooDate.Value.Date
:
list = From x In Me Where x.FooDate.HasValue AndAlso (x.FooDate.Value.Date >= fromDate and x.FooDate.Value.Date <= toDate)
Thanks to both answers for throwing up quick test code to verify that LINQ really does obey AndAlso and force me to look more closely at the original problem.
I'm pretty sure that your query is safe, at least following sample code is:
Dim dateList As New List(Of Nullable(Of Date))
For i As Int32 = 0 To 12
If (i Mod 3 = 0) Then
dateList.Add(Nothing)
Else
dateList.Add(New Date(2012, i, 1))
End If
Next
Dim july = New Date(2012, 7, 1)
Dim fromJuly = (From m In dateList
Where m.HasValue AndAlso m.Value.Date >= july).ToList
Note: If i would replace AndAlso
with And
i would get your exception.
So the problem must be somewhere else. Show us more of your class please.