Monday, September 14, 2009

VB.NET short circuit IF statement and Nullable(of T)

Now this was an interesting bug to find. May be it is not a bug, but I can’t explain this behavior otherwise.

When working with databases and trying to cover impedance mismatch cases it is common to use the following logic:

...
Dim primaryUserId As Integer?
...
Using reader As IDataReader = dataAccess.ExecuteReader("usp_CostCenter_Get", params)
With reader
While .Read()
returnResult = True
costCenter = If(.IsDBNull(0), "", .GetString(0))
description = If(.IsDBNull(1), "", .GetString(1))
primaryUserId = If(.IsDBNull(2), Nothing, .GetInt32(2)) '' <<<<-- incorrect behavior,
'' if condition is true primaryUserId will get 0 instead of Nothing.
'' 0 - is default value for type Integer, but not for type Integer? or Nullable(of Integer)
'' Nothing - should be the correct value in this case.
End While
End With
End Using
...


In case when condition is true you would expect true part of IF statement to execute, while something else happens and primaryUserId receives default value for type Integer not for type Nullable(of Integer) or Integer? .

This is how to correct such behavior:

...
Using reader As IDataReader = dataAccess.ExecuteReader("usp_CostCenter_Get", params)
With reader
While .Read()
returnResult = True
costCenter = If(.IsDBNull(0), "", .GetString(0))
description = If(.IsDBNull(1), "", .GetString(1))

'' expanding IF statement
If .IsDBNull(2) Then
primaryUserId = Nothing
Else
primaryUserId = .GetInt32(2)
End If

End While
End With
End Using
...


Please let me know if you had experienced this before and agree or disagree with me.

Thank you!

1 comment:

  1. I know I'm late to the party on this post, but you're not alone here. I got the same issue but with Nullable Date variables. Needless to say, having date variables assigned to 01/01/0001 instead of Nothing after you did all the work to use Nullable types, sure was confusing/frustrating.

    ReplyDelete