0

Why is this happening. I have two arrays. The first is changed in a function, the second serves as a copy of the first array. But it doesn't work. My code:

function testArray
{
   param
   (
       [parameter(Mandatory=$true)][array]$Board
   )

   $Board[1] = 'X'
   return $Board
}

[array]$test = @('.','.','.','.')
[array]$testCopy = $test

$test = testArray -Board $test

Write-Host $test
Write-Host $testCopy

Output:

. X . .

. X . .

Powershell Version: 5.1

Thanks

I have no idee why it happening.

1 Answer 1

3

You should get familiar with Value Types and Reference Types see this link

Array is a reference type, which mean that when you set the [array]$testCopy = $test you are not creating a new Array but just add a new reference in the memory to the $test array,

so, if you change $test, $testCopy (which is just a reference) will show the value of $test

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, Thankes for you help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.