PowerShell - Strange implicit type conversion

PowerShell is great, but sometimes it has some strange quircks that can cost you a lot of time to solve. My latest "obstacle" was the following situation:

function ArgsToArrayList {
  $al = new-object System.Collections.ArrayList
  $args | foreach { [void] $al.add($_) }
  $al
}

$x = ArgsToArrayList 1 2 3 4 5
write-Host "5 entries, type: " $x.GetType()
$x = ArgsToArrayList
write-Host "0 entries, is null: " ($x -eq $null)

I expect the function ArgsToArrayList to always return an object of type System.Collections.ArrayList, independent of the number of arguments passed. I was wrong.

PowerShell converts the return value of the function ArgsToArrayList from System.Collections.ArrayList to System.Object[] when it contains entries, and to $null when the arraylist is empty.

So the output of the above code is:

5 entries, type: System.Object[]
0 entries, is null: True

Beats me...

6 Comments

  • The arraylist gets enumerated on the pipeline
    you can wrap it to keep in in one piece.

    PoSH> function ArgsToArrayList {
    >> $al = new-object System.Collections.ArrayList
    >> $args | foreach { [void] $al.add($_) }
    >> @(,$al)
    >> }
    >>
    PoSH> $x = ArgsToArrayList 1 2 3 4 5
    PoSH> write-Host "5 entries, type: " $x.GetType()
    5 entries, type: System.Collections.ArrayList

    Yes, this is confusing

    Greetings /\/\o\/\/

  • H PowerShell guy,

    Works great, wrapping into an array of one element leaves the return type alone! So @(,$variable) does the job to keep the original type.

  • Actualy an array of 2 elements ;-) :

    @(,$variable) -eq @($null,$variable)

    so this array get's enumerated the $null is discarded, so the second element the Arraylist survives ;-)

    Greetings /\/\o\/\/

  • Good heavens...

    I already tried with @($variable), but then the type is still converted...

  • +1 (powershell mvp)

  • Is it possible to create a bidimensional arraylist so I can build a structure like below:
    0 1
    [3.535][3535]
    [5.563][5563]
    [2.563][2536]
    [1.253][1253]
    based on this sort ascending by [1]
    Printitng
    1.253
    2.536
    3.535
    5.563

    I would appreciate if some share the code snippet

Comments have been disabled for this content.