Powershell: new decorator: reset variable to the default value

Created on 8 Mar 2020  路  4Comments  路  Source: PowerShell/PowerShell

with the new [default()] we can add default value to variable

PS C:\> [int]$foo = 5
PS C:\> $foo
5
PS C:\> $foo = $null
PS C:\> $foo
0

# now we can

PS C:\> [int][default(10)]$foo = 5
PS C:\> $foo
5
PS C:\> $foo = $null
PS C:\> $foo
10
Issue-Enhancement Resolution-Answered

Most helpful comment

Are there practical use cases for this? I can only imagine this being very confusing and being highly likely to create mistakes. :confused:

All 4 comments

Are there practical use cases for this? I can only imagine this being very confusing and being highly likely to create mistakes. :confused:

for example:

[Bool[]][default($True)]$foo = @($null,$false,$true)
True
False
True

Again, is there a _practical_ use case for this? I can count on two _fingers_ the amount of times I've ever even wanted a boolean array in PS.

I can't really imagine a case where this capability would be a net win for some practical scenario. In the vast majority of cases you just handle this with a parameter to a function or script that has a default value. This setup of automatically exchanging $null value(s) to some arbitrary value whenever a null is encountered doesn't sound useful to me. 馃し鈥嶁檪

Of course, others may feel differently, but I'd prefer to see some practical examples where this addition would be a significant benefit. 馃檪

Note you can already make your own version of this pretty easily:

class MyDefaultAttribute : Management.Automation.ArgumentTransformationAttribute {
    [bool] $Default;

    MyDefaultAttribute([bool] $value) {
        $this.Default = $value
    }

    [object] Transform([Management.Automation.EngineIntrinsics] $engineIntrinsics, [object] $inputData) {
        if ($null -eq $inputData) {
            return $this.Default
        }

        $items = foreach ($item in $inputData) {
            if ($null -eq $item) {
                $this.Default
                continue
            }

            [bool]$item
        }

        return $items
    }
}
[MyDefault($true)]$foo = @($null, $false, $true)
$foo
# True
# False
# True
Was this page helpful?
0 / 5 - 0 ratings