Turning integers to nulls

  • Thread starter Thread starter Jim Owen
  • Start date Start date
J

Jim Owen

I'm a C# guy, recently having to work in VB.Net. I am trying to pass a null
value into an integer property. My code looks like this:
If MyIntVar = 0 Then
MyObject.MyIntProp = Nothing
Else
MyObject.MyIntProp = MyIntVar
End If
When I step through it, the line assigning the property to Nothing is
getting run, but afterward the property is still showing that it is = 0.
Subsequent code fails because this property cannot be 0. How am I supposed
to do this?
 
Jim Owen said:
I'm a C# guy, recently having to work in VB.Net. I am trying to pass a null
value into an integer property. My code looks like this:
If MyIntVar = 0 Then
MyObject.MyIntProp = Nothing
Else
MyObject.MyIntProp = MyIntVar
End If
When I step through it, the line assigning the property to Nothing is
getting run, but afterward the property is still showing that it is = 0.
Subsequent code fails because this property cannot be 0. How am I supposed
to do this?

Value types (such as Int32 and the other basic data types except String)
cannot have a null value. Assigning null to them will simply result in it
being assigned the default value for that type (0 in this case).

You'll have to check for a value of 0 at the point where it would cause
a problem (wouldn't you already have to check if the property is null at
that point anyway?). You could also change your property to type Object,
which could hold either a null reference or an Int32 value, but I'd
recommend the first option, since it's more elegant and will be slightly
faster.

Jeremy
 
Back
Top