What does x?.y?.z mean?

前端 未结 3 2053
感情败类
感情败类 2020-12-02 17:51

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();           


        
3条回答
  •  渐次进展
    2020-12-02 18:34

    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.

提交回复
热议问题