
Copying Nested Arrays w/Array.Copy
Hi,
I have a user-defined data type (structure) which is declared as an
array. Within this structure, there is another structure which is also
declared as an array.
My application needs to hold an original copy of the data, and a
working copy of the data. It does some stuff on the working copy, then
restores it from the original copy to allow the user to try something
different with the original data. In VBv6, this was handled easily
using an equal sign.
In VB.Net, it is different. Everything in the outer level structure
gets copied, however the inner array does not get copied, but rather a
reference to the original is put in place. Thus, if I change
something, perhaps an integer, in the outer level of the working
array, it gets changed only there, where-as if I change something in
the inner working array, it actually changes the data in the original
array.
I've tried Array.Copy as well as the old "=".
The code below demonstrates this.
Has anyone run into this, do you know an alternative means of doing
the array copy?
Thanks,
John
Module Module1
Public Structure fe
Public alpha As Integer
End Structure
Public Structure fi
Public hickory As Integer
Public{*filter*}ory() As fe
End Structure
Sub Main()
Dim fo() As fi
Dim fum() As fi
Dim i As Integer, j As Integer
' Populate the source array (fo)
ReDim fo(1)
For i = 0 To 1
fo(i).hickory = (2 + i) * 1000
ReDim fo(i).dickory(1)
For j = 0 To 1
fo(i).dickory(j).alpha = (4 + i) * 100 + (j + 1) * 10
Next
Next
' Now copy the array
ReDim fum(1)
Array.Copy(fo, fum, 2)
' Now change elements nested in the two arrays...
fo(0).dickory(1).alpha = 444
fum(1).dickory(0).alpha = 333
fo(1).hickory = 222
' Display the results...
Console.WriteLine("fo(1).hickory: " & fo(1).hickory.ToString)
Console.WriteLine("fum(1).hickory: " & fum(1).hickory.ToString)
Console.WriteLine("")
Console.WriteLine("Fo(0).dock(1).alpha: " &
fo(0).dickory(1).alpha.ToString)
Console.WriteLine("Fum(0).dock(1).alpha: " &
fum(0).dickory(1).alpha.ToString)
Console.WriteLine("")
Console.WriteLine("Fum(1).dock(0).alpha: " &
fum(1).dickory(0).alpha.ToString)
Console.WriteLine("fo(1).dock(0).alpha: " &
fo(1).dickory(0).alpha.ToString)
MsgBox("Finished")
End Sub
End Module