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
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.
$x = $null
$result = $x.y # $result is null
$x = New-Object PSObject
$x | Add-Member NoteProperty y 'test'
$result = $x.y # $result is 'test'
It's not pretty but you could add an extension method that will function the way you describe.
public static TResult SafeGet<T, TResult>(this T obj, Func<T, TResult> selector) {
if (obj == null) { return default(TResult); }
else { return selector(obj); }
}
var myClass = new MyClass();
var result = myClass.SafeGet(x=>x.SomeProp);
Haskell has fmap
, which in this case I think is equivalent toData.Maybe.map
. Haskell is purely functional, so what you are looking for would be
fmap select_y x
If x
is Nothing
, this returns Nothing
. If x
is Just object
, this returns Just (select_y object)
. Not as pretty as dot notation, but given that it's a functional language, styles are different.
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
.
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.
This is being added in C# vNext (Roslyn powered C#, releases with Visual Studio 2014).
It is called Null propagation and is listed here as complete. https://roslyn.codeplex.com/wikipage?title=Language%20Feature%20Status
It is also listed here as complete: https://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/3990187-add-operator-to-c
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:
int? length = customers?.Length; // null if customers is null
Customer first = customers?[0]; // null if customers is null
int? count = customers?[0]?.Orders?.Count(); // null if customers, the first customer, or Orders is null
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators