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

Posted by Jay on Stack Overflow See other posts from Stack Overflow or by Jay
Published on 2010-05-28T14:24:31Z Indexed on 2010/05/28 14:52 UTC
Read the original article Hit count: 560

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.y

I can use return x == null ? null : x.y;

Not bad, but that null in the middle always bothers me -- it seems superfluous. I'd prefer something like return x :: x.y;, where what follows the :: is evaluated only if what precedes it is not null.

I see this as almost an opposite to null coalescence, kind of mixed in with a terse, inline null-check, but I'm [almost] certain that there is no such operator in C#.

Are there other languages that have such an operator? If so, what is it called?

(I know that I can write a method for it in C#; I use return NullOrValue.of(x, () => x.y);, but if you have anything better, I'd like to see that too.)

© Stack Overflow or respective owner

Related posts about c#

Related posts about programming-languages