NULLABLE TYPES

Most relational databases have a concept of a null data value. A null value indicates that a field does not contain any data. It lets the database distinguish between valid zero or blank values and non-existing values. For example, a null bank balance would indicate that there is no known balance, while a 0 would indicate that the balance was 0.

You can create a nullable variable in Visual Basic by adding a question mark either to the variable’s name or after its data type. You can also declare the variable to be of type Nullable(Of type). For example, the following code declares three nullable integers:

Dim i As Integer?
Dim j? As Integer
Dim k As Nullable(Of Integer)

To make a nullable variable “null,” set it equal to Nothing. The following code makes variable num_choices null:

num_choices = Nothing

To see if a nullable variable contains a value, use the Is or IsNot operator to compare it to Nothing. The following code determines whether the nullable variable num_choices contains a value. If the variable contains a value, the code increments it. Otherwise the code sets the value to 1.

If num_choices IsNot Nothing Then
    num_choices += 1
Else
    num_choices = 1
End If

Calculations with nullable variables use “null-propagation” rules to ensure that the result makes sense. For example, if a nullable integer contains no value, it probably doesn’t make sense to add another number to it. (What is null plus three?)

If one or more operands in an expression contains a null value, ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.