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

1 Comment

  • hello there and thanks in your information
    I have definitely picked up something new from
    right here. I did then again expertise some technical points using this
    site, as I experienced to reload the website a lot of times previous to I may find out it to
    load properly. I had been puzzling over in case your web host is
    OK No longer that Im complaining, on that the other hand slow loading instances times will often impact
    your placement in google and can injury your quality score if
    advertising and advertisingadvertisingadvertising and with Adwords.
    Well Im including this RSS to my email and could look out
    for a ton extra of your respective exciting content.
    Ensure someone to replace this again very soon.

Comments have been disabled for this content.