Visual Basic .NET Language Null conditional operator


Example

To avoid verbose null checking, the ?. operator has been introduced in the language.

The old verbose syntax:

If myObject IsNot Nothing AndAlso myObject.Value >= 10 Then

Can be now replaced by the concise:

If myObject?.Value >= 10 Then

The ? operator is particularly powerful when you have a chain of properties. Consider the following:

Dim fooInstance As Foo = Nothing
Dim s As String

Normally you would have to write something like this:

If fooInstance IsNot Nothing AndAlso fooInstance.BarInstance IsNot Nothing Then
    s = fooInstance.BarInstance.Baz
Else
    s = Nothing
End If

But with the ? operator this can be replaced with just:

s = fooInstance?.BarInstance?.Baz