boolean operator for safely navigating nested data structures where elements may or may not be null/not present
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 โ€ฆ Wikipedia
๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ Safe_navigation_operator
Safe navigation operator - Wikipedia
1 month ago - It was first used by Groovy 1.0 in 2007 and is currently supported in languages such as C#, Swift, TypeScript, Ruby, Kotlin, Rust, JavaScript, and others. There is currently no common naming convention for this operator, but safe navigation operator is the most widely used term.
Top answer
1 of 3
12

The best you can do is collapse all the member accesses into one function. This assumes without checking that everything is a pointer:

template <class C, class PM, class... PMs>
auto access(C* c, PM pm, PMs... pms) {
    if constexpr(sizeof...(pms) == 0) {
        return c ? std::invoke(pm, c) : nullptr;
    } else {
        return c ? access(std::invoke(pm, c), pms...) : nullptr;
    }
}

Which lets you write:

if (auto r = access(p, &P::q, &Q::r); r) {
    r->doSomething();
}

That's ok. Alternatively, you could go a little wild with operator overloading and produce something like:

template <class T>
struct wrap {
    wrap(T* t) : t(t) { }
    T* t;

    template <class PM>
    auto operator->*(PM pm) {
        return ::wrap{t ? std::invoke(pm, t) : nullptr};
    }

    explicit operator bool() const { return t; }
    T* operator->() { return t; }
};

which lets you write:

if (auto r = wrap{p}->*&P::q->*&Q::r; r) {
    r->doSomething();
}

That's also ok. There's unfortunately no ->? or .? like operator, so we kind of have to work around the edges.

2 of 3
6

"With a little Boilerplate..."

We can get to this:

p >> q >> r >> doSomething();

Here's the boilerplate...

#include <iostream>

struct R {
    void doSomething()
    {
        std::cout << "something\n";
    }
};

struct Q {
    R* r;
};

struct P {
    Q* q;
};

struct get_r {};
constexpr auto r = get_r{};

struct get_q {};
constexpr auto q = get_q{};

struct do_something {
    constexpr auto operator()() const {
        return *this;
    }
};
constexpr auto doSomething = do_something {};

auto operator >> (P* p, get_q) -> Q* {
    if (p) return p->q;
    else return nullptr;
}

auto operator >> (Q* q, get_r) -> R* {
    if (q) return q->r;
    else return nullptr;
}

auto operator >> (R* r, do_something)
{
    if (r) r->doSomething();
}

void foo(P* p)
{
//if (p && p->q && p->q->r)
//    p->q->r->DoSomething();
    p >> q >> r >> doSomething();
}

The resulting assembly is very acceptable. The journey to this point may not be...

foo(P*):
        test    rdi, rdi
        je      .L21
        mov     rax, QWORD PTR [rdi]
        test    rax, rax
        je      .L21
        cmp     QWORD PTR [rax], 0
        je      .L21
        mov     edx, 10
        mov     esi, OFFSET FLAT:.LC0
        mov     edi, OFFSET FLAT:std::cout
        jmp     std::basic_ostream<char, std::char_traits<char> >& std::__ostream_insert<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*, long)
.L21:
        ret
๐ŸŒ
Medium
medium.com โ€บ agilix โ€บ using-the-c-safe-navigation-operator-for-writing-cleaner-code-9e7b462016e2
Using the C# Safe Navigation Operator for writing cleaner code ?. | by Maarten Merken | Agilix | Medium
February 7, 2019 - Using the C# Safe Navigation Operator for writing cleaner code ?. The Elvis-operator ?. (also called the Safe Navigation Operator) can be used to flatten down your syntax tree significantly. The โ€ฆ
๐ŸŒ
Salesforce Developers
developer.salesforce.com โ€บ docs โ€บ atlas.en-us.apexcode.meta โ€บ apexcode โ€บ langCon_apex_SafeNavigationOperator.htm
Safe Navigation Operator | Apex Developer Guide | Salesforce Developers
Use the safe navigation operator (?.) to replace explicit, sequential checks for null references. This operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a NullPointerException.
๐ŸŒ
C# Corner
c-sharpcorner.com โ€บ article โ€บ introduction-to-safe-navigation-operator-in-angular-2
Introduction To Safe Navigation Operator In Angular 2
December 1, 2016 - This operator is very useful to protect against null and undefined values in property paths. This operator allows us to navigate an object path in situations when we are not aware whether a path exists or not.
๐ŸŒ
GitHub
github.com โ€บ tc39 โ€บ proposal-optional-chaining โ€บ issues โ€บ 68
Using the name "safe-navigation" operator instead of "optional-chaining" ยท Issue #68 ยท tc39/proposal-optional-chaining
July 7, 2018 - This name is more intuitive and concise to the purpose and result of the operation, as the user is attempting to safely obtain a member along an object path. Conditional Optional-chaining more closely resembles one of the hacks people used in Javascript to obtain the same effect: ((object || {}).property1 || {}).property2 || null where chaining could either refer to the chain of conditions which must be met, or the chain in the sense of the object path.
Published ย  Jul 07, 2018
Find elsewhere
๐ŸŒ
Nullneuron
gigi.nullneuron.net โ€บ home โ€บ c# 6 preview: the safe navigation operator (?.)
C# 6 Preview: The Safe Navigation Operator (?.) - Gigi Labs
November 10, 2014 - List<string> list = null; int? count = list?.Count; The use of the safe navigation operator involves putting a question mark before the dot operator, as shown above. If list happens to be null (which it is in this case), then the Count property is not accessed, and null is immediately returned.
๐ŸŒ
David Haney
davidhaney.io โ€บ c-probably-getting-new-safe-navigation-operator
C# Probably Getting New "Safe Navigation" Operator "?." :: David Haney - Blogging About .NET Core & Engineering Management
September 29, 2024 - This is due in large part to community demand, which is pretty cool because it shows that the VS team is listening to their customer base; a key part of a successful product. This new operator is likely going to take the syntax of ?. and is known as the Safe Navigation Operator.
๐ŸŒ
Medium
medium.com โ€บ @bhanutp โ€บ use-safe-navigation-operator-with-caution-52127a19dcc0
Use safe navigation operator with caution! | by Bhanu | Medium
January 25, 2024 - Salesforce started supporting the safe navigation operator in Apex from the Winter โ€™21 release. Read more here. You can use the safe navigation operator (?.) instead of explicit, consecutive null reference checks.
๐ŸŒ
CodeProject
codeproject.com โ€บ Articles โ€บ 844687 โ€บ Emulating-the-Safe-Navigation-Operator-in-Csharp-2
Emulating the Safe Navigation Operator in C# - CodeProject
Also, buried inside the definition just before the first angle bracket ('<') is the name of the method - 'NotNull'. The name is not very descriptive, but I couldn't find a more concise and expressive one. It's this method that emulates the functionality of the safe navigation operator.
๐ŸŒ
C# Corner
c-sharpcorner.com โ€บ blogs โ€บ null-conditional-operator-in-c-sharp-60-or-safe-navigation-of-objects
Null Conditional Operator in C# 6.0 or Safe Navigation of Objects
C# 6.0 includes a new null-conditional operator (sometimes called the Safe Navigation Operator): In previous versions null checking for any kind of objects manually we need to write if condition then we need to write our required properties ...
๐ŸŒ
Adobe
helpx.adobe.com โ€บ coldfusion โ€บ using โ€บ language-enhancements.html
Language enhancements
April 27, 2021 - In Adobe ColdFusion (2016 release), the language enhancements that have been introduced are safe navigation operator (โ€œ?.โ€) and collections support along with some other minor enhancements.
๐ŸŒ
Stack Exchange
ell.stackexchange.com โ€บ questions โ€บ 115653 โ€บ why-safe-navigation-operator-instead-of-safe-navigational-operator
modifiers - Why "safe navigation operator" instead of "safe navigational operator"? - English Language Learners Stack Exchange
In English, you can use a noun to modify another noun, like "race horse" or "apple tree" or "navigation operator". ... 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.
๐ŸŒ
Python.org
discuss.python.org โ€บ ideas
Introducing a Safe Navigation Operator in Python - Ideas - Discussions on Python.org
October 6, 2023 - Iโ€™ve been considering the idea of proposing a new feature in Python - a Safe Navigation Operator, similar to whatโ€™s available in languages like JavaScript, Ruby, and C#. Before proceeding with writing a formal PEP, I wanted to bring this up here to gather initial feedback, insights, and ...
๐ŸŒ
Reddit
reddit.com โ€บ r/rust โ€บ c# is getting โ€œ?.โ€, sometimes called the safe navigation operator
r/rust on Reddit: C# is getting โ€œ?.โ€, sometimes called the Safe Navigation Operator
February 2, 2013 - The link says ยท The โ€œ?.โ€ operator is basically saying, if the object to the left is not null, then fetch what is to the right, otherwise return null and halt the access chain.
๐ŸŒ
HandWiki
handwiki.org โ€บ wiki โ€บ Safe_navigation_operator
Safe navigation operator - HandWiki
December 20, 2025 - Clojure doesn't have true operators in the sense other languages uses it, but as it interoperable with Java, and has to perform object navigation when it does, the some->[11] macro can be used to perform safe navigation.