0

In the following snippet I have a minimum viable reproduction of a problem I'm having, I have a function, which returns an arraylist after adding a few items:

function dostuff(){
    $Affixes = [System.Collections.ArrayList]@()
    $Affixes.Add("i1")
    $Affixes.Add("i2")
    $Affixes.AddRange(@("i3","i4"))
    return $Affixes.ToArray()
}

$Affixes = dostuff
$Formatted = $Affixes -join ','

Write-Host $Formatted

The output from this script is unexpected to me:

0,1,i1,i2,i3,i4

Why are there seemingly indexes at the beginning of my output? Why are they prepended like this?

UndyingJellyfish
  • 194
  • 2
  • 15
  • 1
    `ArrayList.Add` returns an `int`. These `int`s end up mingled into your output. Use `[void]` or `| Out-Null` to suppress. (The `return` at the end doesn't do what you think it does: if you leave out the keyword you'll get the same result, as everything these statements produce is part of the output.) – Jeroen Mostert Aug 11 '22 at 11:21
  • 1
    Another way is to replace `[System.Collections.ArrayList]` by `[System.Collections.Generic.List[object]]` which is functionally the same, but doesn't return anything from the `Add*()` methods. So your code will be cleaner and less error-prone. – zett42 Aug 11 '22 at 11:34

0 Answers0