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?
That's one of the differences between C# and VB.NET. In VB.NET
Nothing
does not only meannull
but alsodefault
. So you are assigning the default value ofInt32
to the property what is 0. This is caused by theIf
-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
:or force the nullable with
new Nullable(Of Int32)
:Further read: Why is there a difference in checking null against a value in VB.NET and C#?