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

后端 未结 12 1069
爱一瞬间的悲伤
爱一瞬间的悲伤 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:19

    Delphi has the : (rather than .) operator, which is null-safe.

    They were thinking about adding a ?. operator to C# 4.0 to do the same, but that got the chopping block.

    In the meantime, there's IfNotNull() which sort of scratches that itch. It's certainly larger than ?. or :, but it does let you compose a chain of operations that won't hork a NullReferenceException at you if one of the members is null.

提交回复
热议问题