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[]
#>