Is there an "opposite" to the null coalescing operator? (…in any language?)
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.)
There's the null-safe dereferencing operator (?.) in Groovy... I think that's what you're after.
(It's also called the safe navigation operator.)
For example:
homePostcode = person?.homeAddress?.postcode
This will give null if person
, person.homeAddress
or person.homeAddress.postcode
is null.
(This is now available in C# 6.0 but not in earlier versions)
UPDATE: The requested feature was added to C# 6.0. The original answer from 2010 below should be considered of historical interest only.
We considered adding ?. to C# 4. It didn't make the cut; it's a "nice to have" feature, not a "gotta have" feature. We'll consider it again for hypothetical future versions of the language, but I wouldn't hold my breath waiting if I were you. It's not likely to get any more crucial as time goes on. :-)
If you've got a special kind of short-circuit boolean logic, you can do this (javascript example):
return x && x.y;
If x
is null, then it won't evaluate x.y
.