Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Nullable Integer to String Containing Nothing yields 0

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, of course. NullableInt is Nothing. 

EDIT: Previously I had my code up here so without the explicit conversion to Integer? and everyone seemed to be fixated on/confused by that. There were a lot of suggestions that Option Strict On would catch this type of thing. However, this is actually a quirk of the string-to-integer conversion rules which predate nullable types, but still impact them.

like image 398
Brian MacKay Avatar asked Aug 05 '26 00:08

Brian MacKay


1 Answers

The reason why has to do with the VB.Net conversion rules here. The String type is incompatible with Integer? and hence an conversion takes place. The intermediate step though is converting String to Integer. The VB.Net conversion rules will convert a Nothing or empty String into the Integer value 0. This can be reproduced without nullables

Dim local1 As String = Nothing
Dim local2 As Integer = local1 ' It's 0

This same conversion will then convert the Integer value 0 to the type Integer? which maintains the Integer value.

like image 53
JaredPar Avatar answered Aug 07 '26 17:08

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!