Setting Nullable Integer to String Containing Nothing yields 0
- by Brian MacKay
I've been pulling my hair out over some unexpected behavior from nullable integers.
If I set an Integer to Nothing, it becomes Nothing as expected.
If I set an Integer? to a String that is Nothing, it becomes 0!
Of course I get this whether I explicitly cast the String to Integer? or not.
I realize I could work around this pretty easily but I want to know what I'm missing.
Dim NullString As String = Nothing
Dim NullableInt As Integer? = CType(NullString, Integer?) 'Expected NullableInt to be Nothing, but it's 0!
NullableInt = Nothing 'This works -- NullableInt now contains Nothing. How is this
EDIT: Previously I had my code up here so without the explicit conversion to 'Integer?' and everyone seemed to be fixated on that. I want to be clear that this is not an issue that would have been caught by Option Strict On -- check out the accepted answer. This is a quirk of the string-to-integer conversion rules which predate nullable types, but still impact them.