codymanix
codymanix

Reputation: 29468

Null-Conditional Operator

var a = b?.c.d;

Shouldn't this expression always give a compile error? If b is null, the null value is propagated through so c will also be null and thus also need this operator. In my understanding usage of this operator in an expression spreads viral.

But neither Visual Studio 2015 nor Resharper says anything to me, am I missing something here?

Upvotes: 4

Views: 1006

Answers (4)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

Note that:

var a1 = b?.c.d;

is entirely different from:

var a2 = (b?.c).d;

It is not very easy to explain in short how the unary operator ?. works (yes, unary!). But the idea is that the rest of the "chain" of "operations" is skipped if the expression before ?. is null.

So for a1, you get a null of the compile-time type carried by member d (or Nullable<> of that type if necessary) whenever b happens to be null. When b happens to be non-null, you get the same as b.c.d which may fail if b.c is null.

But a2 is quite different. It will always blow up if b is null, because then the parenthesis (b?.c) will be a null reference, and the next . operator will lead to NullReferenceException. (I am assuming here that c has a reference-type at compile-time.)

So do not think there is a kind of "left-associativity" that makes b?.c.d equivalent to (b?.c).d!


You can find a link to the preliminary C# Language Specification in this answer in another thread; they mention Null-conditional operator as an unary operator in § 7.7.1.

Upvotes: 0

Andrew
Andrew

Reputation: 1596

var a = b == null ? null : b.c.d

This is what that statement would look like in the old way, the ?. operator doesn't look deeper when what is before it is null, it just returns null, you WILL however get an error where b is defined but b.c == null since you didn't write as var a = b?.c?.d.

Upvotes: 0

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

The operator is just syntactic sugar for this:

MyType a = b == null ? 
    null: 
    b.c.d;

Why this should throw a compile-error is unclear to me.

If b is null, the null value is propagated through so c will also be null and thus also need this operator

This isn´t true. Actually when b is null c doesn´t even exist as there´s no instance on which that member could exist. So in short the operator just returns null and omits evaluating c or even d any further.

Upvotes: 4

Oleksandr Kobylianskyi
Oleksandr Kobylianskyi

Reputation: 3380

This operator does short circuit and returns null in case of b is null.

Upvotes: 0

Related Questions