0

Why do I need to declare the type of a variable when assigning it with a list?

In the below code, I need to specify that $firstList is of type list[string], if I don't do that, then its type is Object[], even though in the function returning that list, the list is of type list[string].

function StartProgram
{
    [system.collections.generic.list[string]]$firstList = getList
    $secondList = getList
    Write-Host "firstList is of type $($firstList.gettype())"
    Write-Host "secondList is of type $($secondList.gettype())"
}

function getList
{
    $list = new-object system.collections.generic.list[string]
    $list.Add("foo")
    $list.Add("bar")
    return $list 
}

StartProgram
<#
    Output:
    firstList is of type System.Collections.Generic.List[string]
    secondList is of type System.Object[]
#>
David Klempfner
  • 8,700
  • 20
  • 73
  • 153
  • 1
    Its the return keyword that is throwing you. Check out [this]( http://stackoverflow.com/questions/10286164/powershell-function-return-value). If you check the type of `$list` before the return you will find its the correct object type – Matt Aug 14 '14 at 00:24
  • I took out the return keyword, but it didn't change anything. – David Klempfner Aug 14 '14 at 01:18

1 Answers1

1

PowerShell functions write output to the output stream and when a collection is presented as output, the default behavior is to enumerate the collection and output that. What you get on the other side - when you assign the output to a collection - as an array of objects. That is, the List gets lost during the output operation. You can change this behavior by wrapping the list in an array with it as the single element by changing the return statement to;

return ,$list

or more simply just;

,$list
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • Is it possible to specify an attribute on the function to prevent this "auto-enumeration" feature and simply return the object as-is? – bouvierr Aug 14 '14 at 12:25
  • 1
    No but there may be a feature coming in V5 that will allow you to create a method in a class. Hopefully those `def` methods won't enumerate output but it is too early to say for sure (or even if the feature will even make it into final bits). – Keith Hill Aug 14 '14 at 15:56