Safe navigation operator

In object-oriented programming, the safe navigation operator (also known as optional chaining operator, safe call operator, null-conditional operator, null-propagation operator) is a binary operator that returns null if its first argument is null; otherwise it performs a dereferencing operation as specified by the second argument (typically an object member access, array index, or lambda invocation).

It is used to avoid sequential explicit null checks and assignments and replace them with method/property chaining. In programming languages where the navigation operator (e.g. ".") leads to an error if applied to a null object, the safe navigation operator stops the evaluation of a method/field chain and returns null as the value of the chain expression. It was first used by Groovy 1.0 in 2007[1] and is currently supported in languages such as C#,[2] Swift,[3] TypeScript,[4] Ruby,[5] Kotlin,[6] Rust[7] and others. There is currently no common naming convention for this operator, but safe navigation operator is the most widely used term.

The main advantage of using this operator is that it avoids the pyramid of doom. Instead of writing multiple nested ifs, programmers can just use usual chaining, but add question mark symbols before dots (or other characters used for chaining).

While the safe navigation operator and null coalescing operator are both null-aware operators, they are operationally different.

  1. ^ "Support the optional path operator (?.)". GitHub. Retrieved 2021-01-04.
  2. ^ "Null-conditional Operators (C# and Visual Basic)". Retrieved 2016-01-28.
  3. ^ "Optional Chaining". Retrieved 2016-01-28.
  4. ^ Cite error: The named reference TypeScript - Optional Chaining was invoked but never defined (see the help page).
  5. ^ "Ruby 2.3.0 Released". Retrieved 2016-01-28.
  6. ^ "Null Safety". Retrieved 2016-01-28.
  7. ^ Cite error: The named reference Rust - QuestionMarkOperator was invoked but never defined (see the help page).

Developed by StudentB