Dim nullableInteger as Integer? = NothingThis causes problems when attempting to compare a nullable integer to a regular integer. How do you compare an integer to Nothing?
Does 0 = Nothing or 0 <> Nothing?
Is 1 > Nothing or 1 < Nothing or 1 = Nothing?In my case I was taking a nullable integer in an Entity Framework Model and converting it to an integer in the ViewModel. I converted a Nothing value in the Model to a 0 in the ViewModel. But later when I made changes in the ViewModel I wanted to compare the value in the ViewModel and see if it had changed compared to the original Model value. This was causing me problems.
Dim int As Integer = 0This throws a System.InvalidOperationException("Nullable object must have a value")
Dim nullableInt As Integer? = Nothing
Dim Result as Boolean = (integer <> nullableInt)
I then tried casting the nullable integer to integer. http://stackoverflow.com/a/2228484. Supposedly this would convert a null value to 0.
Dim int As Integer = 0I ended up with the same error.
Dim nullableInt As Integer? = Nothing
Dim Result as Boolean = (integer <> CType(nullableInt, Integer))
Ultimately I ended up finding two different solutions.
Dim int As Integer = 0http://stackoverflow.com/a/2228529
Dim nullableInt As Integer? = Nothing
Dim Result as Boolean = (integer <> If(nullableInt, 0))
Dim int As Integer = 0http://stackoverflow.com/a/10237279
Dim nullableInt As Integer? = Nothing
Dim Result as Boolean = (integer <> nullableInt.GetValueOrDefault)
Either one would allow you to specify the default value to use if the nullable value is null. GetValueOrDefault will take an optional parameter to specify the default value.