Question

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
Was it helpful?

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.

OTHER TIPS

Did you try this?:

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

Hope it helps.

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top