Skip to content

Suggestion: implement null-coalescing, null-conditional access (null-soaking), null-conditional assignment #3240

@mklement0

Description

@mklement0

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 indexing

Re 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 .
  • Rely on the existing behavior with respect to accessing non-existent indices, as implied by the Set-StrictMode setting - see table below.


Related: implement ternary conditionals

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancementthe issue is more of a feature request than a bugResolution-FixedThe issue is fixed.WG-Languageparser, language semantics

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions