-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Description
Null-coalescing and null-conditonal access (null-soaking) would be handy additions to the language.
Update: @BrucePay additionally suggests null-conditional assignment, with ?= - see comment below.
For instance, instead of writing:
if ($null -ne $varThatMayBeNull) { $varThatMayBeNull } else { $fallbackValue }
#
if ($null -ne $varThatMayBeNull) { $varThatMayBeNull.Name } else { $null }one might be able to write:
$varThatMayBeNull ?? $fallbackValue # null-coalescing
#
$varThatMayBeNull?.Name # null-conditional access, for Set-StrictMode -Version 2+
$varThatMayBeNull?[42] # ditto, with indexingRe null-conditional access: With Set-StrictMode being OFF (the default), you can just use $varThatMayBeNull.Name - no special syntax needed; however, if Set-StrictMode -Version 2 or higher is in effect, $varThatMayBeNull.Name would break and that's where the null-conditional operator (?.) is helpful, to signal the explicit intent to ignore the $null in a concise manner.
Open question:
$varThatMayBeNull?[42] handles the case where the variable is $null, but if it isn't, an array element with the specified index must exist.
It would therefore also be helpful to make indexing null-conditional - something that C# does not support, incidentally (you have to use .ElementAtOrDefault()).
The two basic choices are:
-
Come up with additional syntax that explicitly signal the intent to ignore a non-existent index:
- The question is what syntax to choose for this, given that
?[...]and[...]?are not an option due to ambiguity. - Perhaps
[...?], but that seems awkward .
- The question is what syntax to choose for this, given that
-
Rely on the existing behavior with respect to accessing non-existent indices, as implied by the
Set-StrictModesetting - see table below.
Related: implement ternary conditionals