beehaus
beehaus

Reputation: 415

Strange behaviour with strings and arrays

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?

Upvotes: 0

Views: 45

Answers (1)

user2555451
user2555451

Reputation:

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)

Upvotes: 4

Related Questions