Null-Conditional Operators

This is a group of related operators that do a test for #Null on the left operand. These operators help you write less code to do the necessary tests for null. These become very important when you use nested data structures.

.? operator

The operator .? is almost the same as the operator «.». It does a test on the left operand for null before it does a member access operation. If the left operand is null, the result is also null. An example follows:

Var #name = #article.?#author.?name

What follows is the equivalent to the example above without the null-conditional operators.

Var #name As String = #Null
If #article Is Object Then
    Var #author = #article.author
    If #author Is Object Then
        #name = #author.name
    End If
End If

?? operator

The operator ?? is almost the same as the operator «?». It does a test on the result returned by the procedure for null before it calls the method given by the right operand. But if the returned value is null, the result of the expression is also null. An example follows:

Var title = #GetForegroundWindow??#GetFirstChild??GetTitle?

What follows is the equivalent to the example above without the null-conditional operators.

Var #title As String = #Null
Var #window = #GetForegroundWindow?
If #window Is Object Then
    Var #child = #window.#GetFirstChild?
    If #child Is Object Then
        #title = #child.GetTitle?
    End If
End If

(?) operator

The operator «(?)» is almost the same as the element-access operator «()». It does a test for null on the left operand before it gets the element. But if it is null, the result is also null.

An example follows:

Var #name = #article.?#authors(?0).name

What follows is the equivalent to the example above without the null-conditional operators.

Var #name As String = #Null
If #article Is Object Then
    Var #authors = #article.#authors
    If #authors Is Object Then
        #name = #authors(0).name
    End If
End If

|? operator

The operator «|?» is known as the null coalescing operator. It is almost the same as the operators Or Else and If…Then…Else. You use this operator only with nullable variables. If the left operand is not null, this value becomes the result. But if the left operand is null, the right operand becomes the result.

There are other differences between these operators:

An example follows.

Var PageTitle As String = #SuppliedTitle |? "Default Title"

What follows is the equivalent to the example above without the null-conditional operator.

Var PageTitle As String =
    (If #SuppliedTitle Is Object Then #SuppliedTitle Else "Default Title")

See also