Setting Nullable Integer to String Containing Nothing yields 0

Posted by Brian MacKay on Stack Overflow See other posts from Stack Overflow or by Brian MacKay
Published on 2010-12-14T17:09:40Z Indexed on 2010/12/22 15:54 UTC
Read the original article Hit count: 235

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about vb.net