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.)
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.
If you've got a special kind of short-circuit boolean logic, you can do this (javascript example):
If
x
is null, then it won't evaluatex.y
.In Haskell, you can use the
>>
operator:Nothing >> Nothing
isNothing
Nothing >> Just 1
isNothing
Just 2 >> Nothing
isNothing
Just 2 >> Just 1
isJust 1
PowerShell let's you reference properties (but not call methods) on a null reference and it will return null if the instance is null. You can do this at any depth. I had hoped that C# 4's dynamic feature would support this but it does not.
It's not pretty but you could add an extension method that will function the way you describe.
I often need this logic for strings:
The so called "null-conditional operator" has been introduced in C# 6.0 and in Visual Basic 14.
In many situations it can be used as the exact opposite of the null-coalescing operator:
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators