How do I copy an array into another?

Hello,

I want to do something like this: ArrayCopy = Array

Without the original Array changing when I change the CopyArray.

Please help.

Thanks in advance.

richardhaegerAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
gangwischConnect With a Mentor Commented:
Dim ArrayOfInts() As Integer = {1,2,3,4,5,6,7,8,9}
Dim My2ndArrayOfInts() as Integer = ArrayOfInts.Clone()
0
 
Jorge PaulinoConnect With a Mentor IT Pro/DeveloperCommented:
0
 
Jaime OlivaresSoftware ArchitectCommented:
use the Clone() method:

arr2 = arr1.Clone()

considering arr1 and arr2 are defined as arrays
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
Jaime OlivaresSoftware ArchitectCommented:
Oops, too late.
0
 
Stephen MandersonSoftware EngineerCommented:
Use the array.Clone() method

Regards
Steve
0
 
Stephen MandersonSoftware EngineerCommented:
Crap me too :D
0
 
richardhaegerAuthor Commented:
Both solutions worked fine, I gave Paulino less points because he did not include an example. The clone method does a shallow copy. Does CopyTo do a deep copy? I guess so, am I correct?
0
 
Jorge PaulinoIT Pro/DeveloperCommented:
The example was in the MSDN link. I just didn't found usefull to copy/paste. :)

The CopyTo allows to copy to a new array and gives you the possibility to select the start index. Ex from MSDN adapted:

        Dim dinosaurs As New List(Of String)

        dinosaurs.Add("Tyrannosaurus")
        dinosaurs.Add("Amargasaurus")
        dinosaurs.Add("Mamenchisaurus")
        dinosaurs.Add("Brachiosaurus")
        dinosaurs.Add("Compsognathus")

        ' Shows the current array List(Of String)
        Debug.WriteLine(vbLf & "Contents of the dinosaurs :")
        For Each dinosaur As String In dinosaurs
            Debug.WriteLine(dinosaur)
        Next

        ' Declare an array with 15 elements (0 through 14).
        Dim array(14) As String
 
         ' Adds some text to the first position
        array(0) = "OldItem"

        ' Copy the array dinosaurs to the array() starting on 1
        dinosaurs.CopyTo(array, 1)

        Debug.WriteLine(vbLf & "Contents of the array:")
        For Each dinosaur As String In array
            Debug.WriteLine(dinosaur)
        Next


And the results:

Contents of the dinosaurs :
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Compsognathus

Contents of the array:
OldItem
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Compsognathus

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.