0

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
Jeff B
  • 8,572
  • 17
  • 61
  • 140

3 Answers3

0

Did you try this?:

.Age = IIf(dr("age") is DbNull, 10, dr("age"))

Hope it helps.

Sebastian
  • 1,491
  • 6
  • 20
  • 29
0

What value the age can have if it contains null?
I suggest using Nullable(Of Integer) for Age.

Also, compare it against DBNull.Value (which is used for comparison in case the underlying field contains null value).

shahkalpesh
  • 33,172
  • 3
  • 63
  • 88
0

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.

Jeff B
  • 8,572
  • 17
  • 61
  • 140
rism
  • 11,932
  • 16
  • 76
  • 116