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.

?. Member-access operator

The operator «?.» is almost the same as the member-access 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

?() Element-access 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. If the left operand 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

?! Dictionary-access operator

The operator «?!» is almost the same as the dictionary-access operator «!». It does a test for null on the left operand before it gets the value related to the given key. If the left operand is null, the result is also null.

An example follows.

TODO

?? Null-coalescing 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 name As String = #SuppliedName ?? "No name given"

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

Var name As String =
    (If #SuppliedName Is Object Then #SuppliedName Else "No name given")

See also