[RESOLVED] [2005] Copy Array(of Class) to another
I am trying to copy an Array(of Class) to another Array(of Class). The Class really just holds 3 values together, so it's basically a string. I thought just something like this would work
Code:
Dim Array1 as Array(of Class) = Array2
'also tried
Dim Array1 as New Array(of Class)
Array1 = Array2
But that literally makes Array1 access the contents of 2, but I want it to be a separate copy. I'm currently using a simple loop procedure to copy contents but I was hoping there was a command for it. I looked at .Item but there didn't seem to be anything there. Anyone have a solution?
Re: [2005] Copy Array(of Class) to another
Doesnt this work in your situation?
Array.Copy(Array1,Array2)
Re: [2005] Copy Array(of Class) to another
Bulldog, I don't think that Array.Copy does a deep copy of the objects, so for classes (which are reference objects) only the reference will get copied.
I think what would need to be done would be to implement a clone method on the object, something like this:
Code:
Friend Class Blah
Implements ICloneable
Public s1 As String
Public s2 As String
Public s3 As String
Public Function Clone() As Object Implements System.ICloneable.Clone
Return Me.MemberwiseClone
End Function
End Class
Re: [2005] Copy Array(of Class) to another
Yeah, if they were structures, you could copy them with Array.Copy, but since they are reference types there is no shortcut. The reason for this has to do with the fact that there is no 'correct' way to perform a deep copy of reference types, so no language adds that feature. To understand that, consider what would happen if you had an array of classes that wrapped database connections (why you'd do this is beyond me, but it makes a good example). To perform a copy, should new connections be created? Should they be opened? Or should the existing connection be copied? Since different results should happen in different situations, the compiler can't know what to do. Therefore, a shallow copy is all you get. To do more you have to write it yourself.
Re: [2005] Copy Array(of Class) to another
So I guess it can't be done then. Thanks for confirming it though, and to anyone who finds this topic looking for a solution, here's the code I used:
Code:
Public Sub CopyList(ByVal Source As List(Of VocabList), ByVal Destination As List(Of VocabList))
Destination.Clear()
For x As Integer = 0 To Source.Count - 1
Destination.Add(New VocabList(Source(x).Word, Source(x).PartOfSpeech, Source(x).Definition))
Next
End Sub
You would of course replace VocabList with the name of your class and replace New...etc. with your class New Function and its parameters.
Re: [RESOLVED] [2005] Copy Array(of Class) to another
Typically, you's implement a 'clone' method if an object is to be copied. In the Clone method you'd put code in to perform the copy appropriate to the object (as Shaggy stated) and return a new object - a copy of the original one.