Null-conditional operator

var a = b? .cd;

Should this expression always give a compilation error? If b is null, the null value propagates through so that c will also be null and therefore also needs this operator. In my understanding, the use of this operator in an expression is viral.

But neither Visual Studio 2015 nor Resharper tell me anything, did I miss something here?

+4
source share
4 answers

To do this, simply the syntactic sugar operator:

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

Why this should cause a compilation error is not clear to me.

b , , c , ,

. , b null c, , , . null c d .

+4

null b null.

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

, -, ?. , null, null, , , , b b.c == null, var a = b?.c?.d.

0

, :

var a1 = b?.c.d;

:

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

, ?. (, !). , "" "" , ?. null.

, a1 , d ( Nullable<> , ), b . b null, , b.c.d, , b.c null.

a2 . , b null, (b?.c) , . NullReferenceException. ( , c .)

, " ", b?.c.d (b?.c).d!


# ; Null- ยง 7.7.1.

0

Source: https://habr.com/ru/post/1673717/


All Articles