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, then 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, then the result of the expression is 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 operators «Or Else» or «If…Then…Else». You use this operator only with nullable variables. If the left operand is not null, then this becomes the result. But if the left operand is null, then the result becomes the right operand.

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