Home
VB.NET
Array.Copy Example
Updated Mar 10, 2023
Dot Net Perls
Array.Copy. In VB.NET, arrays are initialized to empty memory. But we can copy one array to another with the Array.Copy subroutine.
Copy notes. This function assigns each element in one to each element in another. In this way we effectively initialize arrays.
Example. This program creates 2 five-element arrays. In VB.NET, when we create a five-element array we specify the maximum index of 4. In this program, we assign all 5 elements.
Info Copy() populates the elements of the target array with the elements of the source array. The two arrays are separate in memory.
Sub
So If we change the values in the source array at this point, the target array is not affected by that change.
Finally We use a For-Each loop to display each Integer element in the target array, revealing its contents.
For
Module Module1 Sub Main() ' Source array of 5 elements. Dim source(4) As Integer source(0) = 1 source(1) = 2 source(2) = 3 source(3) = 4 source(4) = 5 ' Create target array and use Array.Copy. Dim target(4) As Integer Array.Copy(source, target, target.Length) ' Display target array. For Each element As Integer In target Console.WriteLine(element) Next End Sub End Module
1 2 3 4 5
Several overloads of Array.Copy are available. The simplest overload is shown above—it copies a specified number of elements starting at the first element from one array to another.
And With other overloads, we can specify a sourceIndex and a destinationIndex. This makes it possible to copy a range of elements at an offset.
Tip Using the simplest overload for the required task is ideal. But some programs are simpler overall with the complex overloads.
Summary. Arrays are powerful. With Array.Copy, and related subroutines such as Array.Resize, we manually manipulate arrays—their lengths and their elements.
Array.Resize
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 10, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen