Is there an “opposite” to the null coalescing operator? (…in any language?)

后端 未结 12 1062
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 18:38

null coalescing translates roughly to return x, unless it is null, in which case return y

I often need return null if x is null, otherwise return x

12条回答
  •  庸人自扰
    2020-12-04 19:20

    The so called "null-conditional operator" has been introduced in C# 6.0 and in Visual Basic 14.
    In many situations it can be used as the exact opposite of the null-coalescing operator:

    int? length = customers?.Length; // null if customers is null   
    Customer first = customers?[0];  // null if customers is null  
    int? count = customers?[0]?.Orders?.Count();  // null if customers, the first customer, or Orders is null
    

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators

提交回复
热议问题