user2005848 user2005848 - 1 month ago 11
Vb.net Question

Why are arrays sometimes linked?

Something like this works as expected:

Dim test(1) As Integer
test = {1, 2}
Dim test2(1) As Integer
test2 = test
test = {3, 4}
test2 = {4, 5}


But sometimes after setting one array to be equal to another, the changes to one will affect the other. This forces me to add
.clone
everywhere. Why is this?

Answer

The code test2 = test makes the two variables test2 and test point to the same array. If you made any changes to the array like:

test2(1) = 0
test(0) = 99

Then both those changes would be visible via both test and test2, because they are the same array.

However, when you do:

test = {3, 4}

You are not altering the existing array; you are creating a new one and making test point to it. It works the same way as test2 = test - you're redirecting which array the variable points to.

So then you're back to having two separate arrays, and changes in one are not reflected in the other.