PowerShell - function return values implementing IEnumerable are decomposed into an array
In this blog post I wrote about (by me) unexpected implicit type conversion on return values of functions which is actually really cool: all types returned that implement the IEnumerable interface are decomposed in an array of the elements that are enumerated in the IEnumerable type. This collection of elements is returned "on the pipeline". This decompositioning goes one level deep (a pipeline is linear). So if an array of values is returned, the values don't get decomposed. An array with a single element can be returned as follows: ,$element.
An example follows below with two functions: foo where the return value gets decomposed into an array, and bar where we stoped the decompositioning by returning the element in an array:
function foo
{
$arraylist = new-Object System.Collections.ArrayList
[void]$arraylist.Add("one")
[void]$arraylist.Add("two")
[void]$arraylist.Add("three")
return $arraylist # implicit conversion to array
}
function bar
{
$arraylist = new-Object System.Collections.ArrayList
[void]$arraylist.Add("one")
[void]$arraylist.Add("two")
[void]$arraylist.Add("three")
return ,$arraylist
}
foo | foreach ($_) {Write-Host "foo value (with type: $($_.GetType()) in pipe: $_" }
bar | foreach ($_) {Write-Host "bar value (with type: $($_.GetType()) in pipe: $_" }
This results in:
foo value (with type: System.String in pipe: one
foo value (with type: System.String in pipe: two
foo value (with type: System.String in pipe: three
bar value (with type: System.Collections.ArrayList in pipe: one two three