I'm confused about how the null-conditional operator cascades with normal property access. Take these two examples:
a?.b.c
(a?.b).c
I would expect them to be equivalent: first, the value of a?.b
is evaluated, then result.c
is evaluated. Thus if a == null
, an exception should be thrown.
However, that only happens in the second expression. The first expression evaluates to null
, meaning it's the same as a?.b?.c
. Why?
That's only a matter of operator precedence. Let's go through the cases:
a
=>null
is returned, nothing else is evaluated given that the null-conditional operators are short-circuiting.a
=>null
is returned((B)null).c
=>NullReferenceException
is thrownFor these cases to be equivalent, you should be comparing
a?.b.c
(a?.b)?.c
a?.b?.c
(as you already mentioned)