Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 286
Jay Avatar asked May 28 '10 14:05

Jay


People also ask

What is a null-coalescing operator used for?

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.

Which of the following is the null-coalescing operator?

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.

What is null conditional and null coalescing?

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.

What is the symbol of the null-coalescing 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.


1 Answers

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)

like image 158
Jon Skeet Avatar answered Sep 22 '22 17:09

Jon Skeet