Sorizon
Sorizon

Reputation: 43

Adding to one element in array results in adding to all elements

I have the following:

$p = New-Object PSObject -Property @{PIndex = New-Object System.Collections.ArrayList}
[System.Collections.ArrayList]$pa = @($p) * 5

I want the array $pa (containing the $p object) to be of fixed size. So far all looks good. But when I add elements to PIndex of one member of array $pa, it adds the same elements to all the other members of $pa. So, I do this:

$pa[0].PIndex.Add(2)

Lets check:

PS C:\Users> $pa[0].PIndex
2
PS C:\Users> $pa[1].PIndex
2
PS C:\Users> $pa[2].PIndex
2

And so on. Just want to add elements to PIndex array of $pa[0]. Why is it also adding to the other members ? Am I missing a syntax ?

Type looks fine:

PS C:\Users> $pa.GetType()

IsPublic IsSerial Name                                     BaseType                                                                            
-------- -------- ----                                     --------                                                                            
True     True     ArrayList                                System.Object                                                                       

Thanks..

Upvotes: 0

Views: 37

Answers (1)

EBGreen
EBGreen

Reputation: 37730

In your code you create one object ($p) then you assign that one object to five different locations in the arraylist. If you want five different objects then you need to create five different objects:

$pa = New-Object System.Collections.ArrayList
for($i=1;$i -le 5;$i++){
    $p = New-Object PSObject -Property @{PIndex = New-Object System.Collections.ArrayList}
    $pa.Add($p)
}

Upvotes: 1

Related Questions