Possible pitfalls of using this (extension method based) shorthand

后端 未结 11 1451
孤独总比滥情好
孤独总比滥情好 2020-11-27 20:00

C#6 Update

In C#6 ?. is now a language feature:

// C#1-5
propertyValue1 = myObject != null ? myObject.StringProperty : null; 

// C#         


        
11条回答
  •  清歌不尽
    2020-11-27 20:08

    Not an answer to the exact question asked, but there is Null-Conditional Operator in C# 6.0. I can argue it will be a poor choice to use the option in OP since C# 6.0 :)

    So your expression is simpler,

    string propertyValue = myObject?.StringProperty;
    

    In case myObject is null it returns null. In case the property is a value type you have to use equivalent nullable type, like,

    int? propertyValue = myObject?.IntProperty;
    

    Or otherwise you can coalesce with null coalescing operator to give a default value in case of null. For eg,

    int propertyValue = myObject?.IntProperty ?? 0;
    

    ?. is not the only syntax available. For indexed properties you can use ?[..]. For eg,

    string propertyValue = myObject?[index]; //returns null in case myObject is null
    

    One surprising behaviour of the ?. operator is that it can intelligently bypass subsequent .Member calls if object happens to be null. One such example is given in the link:

    var result = value?.Substring(0, Math.Min(value.Length, length)).PadRight(length);
    

    In this case result is null if value is null and value.Length expression wouldn't result in NullReferenceException.

提交回复
热议问题