Copying Arrays (Part 2)

by Oct 1, 2015

In a previous tip we explained how you can safely "clone" an array using Clone() method. This will copy the content of an array to a new array.

However, if the array elements were objects (and not primitive data like numbers or strings), the array stores the memory position of these objects, so cloning will create a new array, but the new array will still reference the same objects. Have a look:

$object1 = @{Name='Weltner' ID=12 }
$object2 = @{Name='Frank' ID=99 }


$a = $object1, $object2
$b = $a.Clone()
$b[0].Name = 'changed'
$b[0].Name
$a[0].Name 

Even though you cloned array $a, the new array $b still references the same objects, and changes to the objects would affect both arrays. Only changes to the array content would be isolated:

$object1 = @{Name='Weltner' ID=12 }
$object2 = @{Name='Frank' ID=99 }


$a = $object1, $object2
$b = $a.Clone()
$b[0] = 'deleted'
$b[0]
$a[0]

Twitter This Tip! ReTweet this Tip!