Search code examples
c#.netnull-conditional-operator

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?


Solution

  • 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.