Search code examples
vb.netado.netdatatableternary-operatordbnull

Populating Object from DataTable with default value when DBNull


I am populating the customer object as shown below. How do I would I concisely code something like the following?

If IsDbNull(.Age) Then 
  .Age = 10
Else
  .Age = dataRow("Age")
End If 

Here's the context I'd like to use it in:

Public Shared Function Retrieve() As List(Of Customer)

  Dim dt As DataTable = Dac.ExecuteDataTable("CustomerRetrieveAll", Nothing)
  Dim customerList As New List(Of Customer)

  For Each dr As DataRow In dt.Rows 
    customerList.Add(New Customer {
                       .CustomerId = CType(dr("CustomerID"), Integer),
                       .LastName = dr("LastName").ToString,
                       .Age = dr("Age").ToString,
                       .FirstName = dr("FirstName").ToString})  
  Next

  Return customerList 
End Function

Solution

  • Within the Microsoft.VisualBasic namespace there is a function called IIF. It works by evaluating an expression and returning one value if the expression is true and another if false.

    So

    .Age = IIF(dr("Age") = DBNull.Value, 10, dr("Age").ToString())
    

    In newer versions of Visual Studio (2008 ~), this is available by default without import an import (IIF was a function, the new If is an operator):

    .Age = If(dr("Age") = DBNull.Value, 10, dr("Age").ToString())
    

    If it wasn't DBNull, but just Nothing, you could use the null-coalescing operator:

    Dim val = If(objectThatMightBeNothing, DefaultValueToUse)
    

    See MSDN for more detail.