I understand Powershell arrays are immutable objects and like all objects, are passed by reference to functions. But what I don't understand in the below example is why $b doesn't have the same values as $a.
The only difference is that $b is not strongly typed. Does that mean that Test-ByRefArray casts $b from [object[]] to [string[]], a new object is actually created, which would explain why changes made by Test-ByRefArray on this new object have no impact on the original object ?
function Test-ByRefArray {
param (
[string[]] $Array1,
[string[]] $Array2
)
$Array1[0] = "Modified by Test-ByRefArray"
$Array2[0] = "Modified by Test-ByRefArray"
}
function Test-Array {
[string[]] $a = 'hello', 'world'
$b = 'hello', 'world'
$c = $a #by ref: if a is updated, so is $c
Test-ByRefArray -Array1 $a -Array2 $b
$a -join ", "
$b -join ", "
$c -join ", "
}
Test-Array
Output:
Modified by Test-ByRefArray, world
hello, world
Modified by Test-ByRefArray, world