Safe Navigation (?.) Operator

Summary

Gets the class member if the object (left-hand side) is not null.

Syntax

identifier1 ?. identifier2

Parameters

identifier1
Any legal expression.
identifier2
Any legal expression.

Description

The safe navigation operator can be used to substitute for checking for null and undefined:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Foo
{
    void bar() {}
}
 
Foo? foo = null;
 
// The following code (if it were legal JS++):
if (foo != null) {
    return foo.bar();
}
else {
    return null;
}
// is the same as:
foo?.bar();

The safe navigation operator applies to both existent types and nullable types.

If the object (left-hand side) of the expression evaluates to null, the null value will be returned. If the object (left-hand side) of the expression evaluates to undefined, the undefined value will be returned.

Examples

Usage with Existent Types
1
2
3
4
5
6
7
8
9
10
11
12
import System;
 
class Foo
{
    void doSomething() {
        Console.log("Something happened.");
    }
}
 
Foo[] arr = [ new Foo ];
Foo+ foo = arr[Math.random(100)];
foo?.doSomething();
Usage with Nullable Types
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import System;
 
class Foo
{
    Foo? maybe() {
        if (Math.random() > 0.5) {
            return this;
        }
        else {
            return null;
        }
    }
 
    void log() {
        Console.log("Something happened.");
    }
}
 
auto foo = new Foo();
foo.maybe()?.log();

See Also

Share

HTML | BBCode | Direct Link