You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Returning nothing (Automation.Null) from an [object]-typed custom-class method breaks #7128
Note that & {} outputs "nothing", i.e., the "null collection" [System.Management.Automation.Internal.AutomationNull]::Value
Expected behavior
Given that PowerShell allows casting any value to [object] - including $null and [System.Management.Automation.Internal.AutomationNull]::Value, the operation should succeed and the [System.Management.Automation.Internal.AutomationNull]::Value) should be passed through.
[...] the code that invokes the scriptblock expects there to be an object in the result List i.e. result.Count == 1. There are no objects in the pipeline case so you get an index-out-of-range error. [...]
BTW - the code in question is here.
Environment data
PowerShell Core v6.1.0-preview.2 on macOS 10.13.4
PowerShell Core v6.1.0-preview.2 on Ubuntu 16.04.4 LTS
PowerShell Core v6.1.0-preview.2 on Microsoft Windows 10 Pro (64-bit; Version 1709, OS Build: 16299.371)
Windows PowerShell v5.1.17134.48 on Microsoft Windows 10 Pro (64-bit; Version 1709, OS Build: 16299.371)
Thanks Bruce Payette (@BrucePay)
The one thing I don't like every time I should check for $null before iterating(in case if my method should return array) because:
$null | Foreach-Object { $_.someprop.prop = "some value" } # throws exception;
&{} | Foreach-Object { $_.someprops.prop } # no throw because no iterating;
so it means that after each call which return enumerable. I should check like:
class Foo { [object] Bar() { return $somedata | Where-Object { <# filter data #> } };
$myarray = (new Foo).Bar()
if($myarray){
$myarray | Foreach-Object { <# process data #> }
}
but it would be great to write just code in pipeline: $myarray = (new Foo).Bar() | Foreach-Object { <# process data #> }
Activity
BrucePay commentedon Jun 21, 2018
Rather than generating an error which wouldn't have been very useful, I changed the code to return default(T).
mklement0 commentedon Jun 22, 2018
Thanks, Bruce Payette (@BrucePay), that makes sense.
To spell it out, in the case of
[object]- and any reference type - this will default to$null- see https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/default-value-expressions for the full story.winperec commentedon Jun 26, 2018
Thanks Bruce Payette (@BrucePay)
The one thing I don't like every time I should check for $null before iterating(in case if my method should return array) because:
so it means that after each call which return enumerable. I should check like:
but it would be great to write just code in pipeline:
$myarray = (new Foo).Bar() | Foreach-Object { <# process data #> }