Friday, August 19, 2016

Comparing Nullable Integer to Integer.

I only recently found out that you can create nullable integers. In other words, the value of your integer variable can be Nothing.
Dim nullableInteger as Integer? = Nothing
This 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 = 0
Dim nullableInt As Integer? = Nothing
Dim Result as Boolean = (integer <> nullableInt)
This throws a System.InvalidOperationException("Nullable object must have a value")
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 = 0 
Dim nullableInt As Integer? = Nothing 
Dim Result as Boolean = (integer <> CType(nullableInt, Integer))
I ended up with the same error.

Ultimately I ended up finding two different solutions.
Dim int As Integer = 0 
Dim nullableInt As Integer? = Nothing 
Dim Result as Boolean = (integer <> If(nullableInt, 0))
http://stackoverflow.com/a/2228529
Dim int As Integer = 0 
Dim nullableInt As Integer? = Nothing 
Dim Result as Boolean = (integer <> nullableInt.GetValueOrDefault)
http://stackoverflow.com/a/10237279

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.