
Using a Nullable Type Variable
The most important members of a nullable type are its HasValue and Value properties. For a variable of a nullable type, HasValue tells you whether the variable contains a defined value. If HasValue is True, you can read the value from Value. Note that both HasValue and Value are ReadOnly properties.
Default Values
When you declare a variable with a nullable type, its HasValue property has a default value of False. This means that by default the variable has no defined value, instead of the default value of its underlying value type. In the following example, the variable numberOfChildren initially has no defined value, even though the default value of the Integer type is 0.
Dim numberOfChildren? As Integer
A null value is useful to indicate an undefined or unknown value. If numberOfChildren had been declared as Integer, there would be no value that could indicate that the information is not currently available.
Storing Values
You store a value in a variable or property of a nullable type in the typical way. The following example assigns a value to the variable numberOfChildren declared in the previous example.
If a variable or property of a nullable type contains a defined value, you can cause it to revert to its initial state of not having a value assigned. You do this by setting the variable or property to Nothing, as the following example shows.
numberOfChildren = Nothing
Note: |
|---|
Although you can assign
Nothing to a variable of a nullable type, you cannot test it for Nothing by using the equal sign. Comparison that uses the equal sign, someVar = Nothing, always evaluates to Nothing. You can test the variable's HasValue property for False, or test by using the Is or IsNot operator.
|
Retrieving Values
To retrieve the value of a variable of a nullable type, you should first test its HasValue property to confirm that it has a value. If you try to read the value when HasValue is False, Visual Basic throws an InvalidOperationException exception. The following example shows the recommended way to read the variable numberOfChildren of the previous examples.
If numberOfChildren.HasValue Then
MsgBox("There are " & CStr(numberOfChildren) & " children.")
Else
MsgBox("It is not known how many children there are.")
End If