Array.Copy Method

   
Array.Copy Method

Class

System.Array

Syntax

 Array.Copy(   sourceArray   ,   destinationArray   ,   length   ) Array.Copy(   sourceArray   ,   sourceIndex   ,   destinationArray   , _   destinationIndex   ,   length   ) 
sourceArray (required; any array)

The array to be copied

sourceIndex (required in second overloaded version; integer)

The index in sourceArray at which copying begins

destinationArray (required; any array)

The target array

destinationIndex (required in second overloaded version; Integer)

The index in destinationArray where the first element is to be copied

length (required; Integer)

The number of elements to copy

Return Value

None

Description

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.

Rules at a Glance

  • 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 .

Example

 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 

VB.NET/VB 6 Differences

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.

   


VB.Net Language in a Nutshell
VB.NET Language in a Nutshell
ISBN: B00006L54Q
EAN: N/A
Year: 2002
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net