Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The draft spec for Pattern Matching in C# contains the following code example:

Type? v = x?.y?.z; 
if (v.HasValue) {
    var value = v.GetValueOrDefault();     
    // code using value 
} 

I understand that Type? indicates that Type is nullable, but assuming x, y, and z are locals, what does x?.y?.z mean?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
134 views
Welcome To Ask or Share your Answers For Others

1 Answer

Be aware that this language feature is only available in C# 6 and later.

It's effectively the equivalent of:

x == null ? null
   : x.y == null ? null
   : x.y.z

In other words, it's a "safe" way to do x.y.z, where any of the properties along the way might be null.

Also related is the null coalescing operator (??), which provides values to substitute for null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...