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...

Published Monday, February 05, 2007 11:19 PM by svdoever
Filed under:

Comments

Tuesday, February 06, 2007 4:29 AM by /\/\o\/\/

# re: PowerShell - Strange implicit type conversion

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\/\/

Tuesday, February 06, 2007 7:28 AM by svdoever

# re: PowerShell - Strange implicit type conversion

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.

Tuesday, February 06, 2007 9:00 AM by /\/\o\/\/

# re: PowerShell - Strange implicit type conversion

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\/\/

Tuesday, February 06, 2007 9:08 AM by svdoever

# re: PowerShell - Strange implicit type conversion

Good heavens...

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

Wednesday, February 07, 2007 10:54 AM by vincent

# re: PowerShell - Strange implicit type conversion

+1 (powershell mvp)

Wednesday, August 05, 2009 10:46 PM by virgilio

# re: PowerShell - Strange implicit type conversion

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

Leave a Comment

(required) 
(required) 
(optional)
(required)