Why is my Nullable(Of Int32) = 0 after I set it to Nothing?

1.3k views Asked by At

I think I'm missing something fundamental about nullable types. Hopefully this example will open up new understanding, but at the very least, maybe we can get this one thing working right.

In a Class (a dialog form), I declare:

Property ProductStructureHeaderKey As Int32?

In another Class, I declare an instance of that dialog and attempt to set that Property with this line:

    dr.ProductStructureHeaderKey = If(parentRow.Cells(1).Value Is Nothing, Nothing, Int32.Parse(parentRow.Cells(1).Value))

When that line assigns Nothing to the property, the property is equal to 0. (And then later, it's passing 0 to the DB when I want it passing NULL.)

That's not what I expect and I keep finding code (SO, MSDN, etc) that looks like I'm doing things right, but clearly, I'm not. So, friends, what am I doing wrong? How do I employ Nullable types to meet my needs?

1

There are 1 answers

4
Tim Schmelter On BEST ANSWER

That's one of the differences between C# and VB.NET. In VB.NET Nothing does not only mean null but also default. So you are assigning the default value of Int32 to the property what is 0. This is caused by the If-operator that has to infer the type from the two values not from the property that you want to assign.

Instead use either an If...Else:

If parentRow.Cells(1).Value Is Nothing Then
    dr.ProductStructureHeaderKey = Nothing ' Now it's not 0 but Nothing
Else
    dr.ProductStructureHeaderKey = Int32.Parse(parentRow.Cells(1).Value)
End If

or force the nullable with new Nullable(Of Int32):

dr.ProductStructureHeaderKey = If(parentRow.Cells(1).Value Is Nothing, new Nullable(Of Int32), Int32.Parse(parentRow.Cells(1).Value))

Further read: Why is there a difference in checking null against a value in VB.NET and C#?