0

Here I assign the value of an array to a variable, I then alter the variable, the array changes also.

$TestArray = @{ "ValueA" = "A" ; "ValueB" = "B" ; "Number" = "" }
$TestNumbers = 1..10

foreach ($number in $testnumbers) {

    $results = $TestArray
    $results.Number = $number
    Write-Host $TestArray.Number

}

I thought that $results = $TestArray would take a copy of $TestArray but this test shows that modifying $results also changes the corresponding value in $TestArray

Can anyone help me understand this behavior?

1 Answer 1

4

Doing:

$results = $TestArray

will make $results a reference to the same object referred to by TestArray. So, if you change one, the other will also be affected because they are the same object.


To instead make $results a copy of $TestArray, you can use its Clone method:

$results = $TestArray.Clone()

Also, just for the record, $TestArray is not actually an array. It is a hashtable (also called a hashmap) where keys are paired with values. An array would be something like:

$TestArray = (1, 2, 3)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I am really surprised that I have only just noticed this behaviour. It makes sense. I am wondering is the reference behaviour applicable to all strings arrays hashtables and objects?
It depends on if the object in question can be mutated or not. If it is something like a hashtable, then yes, because you can add/remove items from it. If it is an immutable object such as a string, then no because strings cannot be changed (all operations on them produce new objects instead of modifying the old ones). Here is an explanation on the difference between mutable objects and immutable ones: en.wikipedia.org/wiki/Immutable_object.

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.