0

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

7
  • 1
    You're passing by reference instead of by value. When you edit one, you edit them all. Commented Jun 25, 2018 at 19:23
  • Also, $pa is an arraylist not an array. Commented Jun 25, 2018 at 19:30
  • Reference/Value doesn't answer the question. Each member is distinct. I am pointing to a specific member. When I refer to $pa[0], I am not referring to $pa[1] or any other. Maybe the syntax.. Commented Jun 25, 2018 at 19:37
  • 1
    Each is not distinct. that is why changing one is changing all. You have essentially added one object to the arraylist five times. Commented Jun 25, 2018 at 19:39
  • 1
    Do this if you want to add five different objects: $pa = New-Object System.Collections.ArrayList;1..5 | %{$p = New-Object PSObject -Property @{PIndex = New-Object System.Collections.ArrayList}; $pa.Add($p)} Commented Jun 25, 2018 at 19:43

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you.... will go with your suggestion (did have similar code with creating new object instances in a loop elsewhere in my program. Was trying to shortcut it with $pa = @($p) * 5 )... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.