Array.Copy Method |
System.Array
Array.Copy( sourceArray , destinationArray , length ) Array.Copy( sourceArray , sourceIndex , destinationArray , _ destinationIndex , length )
The array to be copied
The index in sourceArray at which copying begins
The target array
The index in destinationArray where the first element is to be copied
The number of elements to copy
None
Makes a copy of all or part of an array.
Since arrays are reference types, when we set one array variable equal to another, we are just assigning a new reference to the same array. For instance, consider the following code:
Dim a( ) As Integer = {1, 2, 3} Dim b( ) As Integer ' Array assignment b = a ' Change b b(0) = 10 ' Check a MsgBox(a(0)) 'Displays 10
The fact that changing b(0) also changes a(0) shows that a and b point to the same array.
Using the first syntax, you can copy a range of values from the beginning of sourceArray to the beginning of destinationArray . Using the second syntax, you can copy a range of values from anywhere in destinationArray to anywhere in targetArray .
sourceArray and destinationArray must have the same number of dimensions.
length is the total number of elements to be copied. If sArr1 is a two- dimensional array, for example, the statement:
Array.Copy(sArr1, 0, sArr2, 0, 3)
copies the values from sArr(0,0), sArr(0,1), and sArr(1,0) to sArr2.
To copy all elements, you can supply UBound(sourceArray) + 1 as an argument to length .
If sourceArray and destinationArray are the same, and destinationIndex lies within the range of values being copied (that is, if the source and target ranges overlap), no data will be lost. The method behaves as if it copies length elements from sourceArray to a temporary buffer, then copies from the temporary buffer to destinationArray .
Dim a( ) As Integer = {1, 2, 3} Dim c( ) As Integer ' Array copy ReDim c(UBound(a) + 1) Array.Copy(a, c, UBound(a) + 1) 'Change c c(0) = 20 'Check a MsgBox(a(0)) 'Displays 1
Since arrays were not a reference type in VB 6, you could simply create a copy of an existing array through assignment, thus eliminating the need for a Copy method.