Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a List[String] using a comma vs not using a comma

Tags:

powershell

how does putting a comma before a list affect its type?

Have a look at the following code:

function StartProgram
{
    $firstList = getListMethodOne
    Write-Host "firstList is of type $($firstList.gettype())"

    $secondList = getListMethodTwo
    Write-Host "secondList is of type $($secondList.gettype())"
}

function getListMethodOne
{
    $list = new-object system.collections.generic.list[string]
    $list.Add("foo") #If there is one element, $list is of type String
    $list.Add("bar") #If there is more than one element, $list is of type System.Object[]
    return $list 

}

function getListMethodTwo
{
    $list = new-object system.collections.generic.list[string]
    $list.Add("foo")
    $list.Add("bar")
    return ,$list #This is always of type List[string]
}

StartProgram

Why is it, if you don't use a comma before returning $list in getListMethodOne it returns as type System.Object[], whereas if you do use a comma as in getListMethodTwo, it is of type List[string] as expected?

PS: I'm using PSVersion 4.0

like image 732
David Klempfner Avatar asked Aug 13 '14 06:08

David Klempfner


1 Answers

When you return collection, than PowerShell is kind enough to unravel it for you. Unary comma creates collection with single element, so "external" collection gets unraveled and collection you want to return is kept.

I blogged about it a while ago.

Two more things:

  • return is used in PowerShell to leave function early, it's not needed to return something from function (any not captured output is returned)
  • in PowerShell 4.0 you can use Write-Output -NoEnumerate $collection to prevent unraveling your collection.
like image 188
BartekB Avatar answered Nov 15 '22 06:11

BartekB