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, the result is a null value. For example, if num_choices in the previous example contains a null value, then num_choices + 1 is also a null value. (That’s why the previous code checks explicitly to see whether num_choices is null before incrementing its value.)

Example program NullableTypes, which is available for download on the book’s website, demonstrates nullable types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.14.243