Search code examples
vb.netnullabledbnull

VB.NET: How do I use coalesce with db column values and nullable types? Or is there a better solution?


I'm trying to do something similar to what's described here, but with nullable types.

http://www.csharp-station.com/Tutorials/Lesson23.aspx

int availableUnits = unitsInStock ?? 0;

In VB, it would be this:

Dim availableUnits As Int32 = If(unitsInStock, 0)

However I'm working with db columns, which could be DbNull, and nullable types, which can be Nothing (which is different to DbNull). If a column is DbNull, I want to return Nothing, otherwise return the value. For eg:

Dim availableUnits As Int32? = If(myDataReader("UnitsInStock").Value, Nothing)

The error I'm getting is "Specified cast is not valid" but I'm not sure why. I've tried this as well:

Dim availableUnits As Int32? = If(isDbNull(myDataReader("UnitsInStock").Value), myDataReader("UnitsInStock").Value, Nothing)

Which is messy and just results in the same error. The only thing that works is this:

Dim availableUnits As Int32?
If isDbNull(myDataReader("UnitsInStock").Value) Then
  availableUnits = myDataReader("UnitsInStock").Value
Else
  availableUnits = Nothing
End If

Which is just silly. Is there a better way of getting nullable db values into nullable variables that I'm not aware of?


Solution

  • It is silly, but you have to cast the Nothing when you set it:

    Dim availableUnits As Int32? = If(myDataReader.IsDBNull("UnitsInStock"), _
                                      CType(Nothing, Int32?), _
                                      myDataReader.GetInt32("UnitsInStock"))