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#.
(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.)
A null-coalescing operator is used to check such a variable (of nullable type) for null. If the variable is null, the null-coalescing operator is used to supply the default value while assigning to a variable of non-nullable type.
Introduction. The ?? operator is also known as the null-coalescing operator. It returns the left side operand if the operand is not null else it returns the right side operand.
In cases where a statement could return null, the null-coalescing operator can be used to ensure a reasonable value gets returned. This code returns the name of an item or the default name if the item is null. As you can see, this operator is a handy tool when working with the null-conditional operator.
Kotlin uses the ?: operator. This is an unusual choice of symbol, given that ?: is typically used for the Elvis operator, not null coalescing, but it was inspired by Groovy (programming language) where null is considered false.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With