Is this the proper way to deep clone a class?
This seems to work, but is it the best way to implement a deep clone?
Code:
Public Class Person
Public Property name() As String
Public Property numbers As List(Of Integer)
Public Function MakeACopy() As Person
Dim newone As Person
newone = DirectCast(Me.MemberwiseClone(), Person)
newone.numbers = New List(Of Integer)
For i = 0 To Me.numbers.Count - 1
newone.numbers.Add(Me.numbers(i))
Next
Return newone
End Function
End Class
Module Module1
Sub Main()
Dim Aperson As New Person
Aperson.name = "Alpha"
Aperson.numbers = New List(Of Integer)
For i = 1 To 5
Aperson.numbers.Add(i)
Next
Dim Bperson As New Person
Bperson = Aperson.MakeACopy
Bperson.name = "Beta"
Console.WriteLine(Aperson.name & ":" & Bperson.Name)
Bperson.numbers.Clear()
For i = 6 To 10
Bperson.numbers.Add(i)
Next
For i = 0 To 4
Console.WriteLine(Aperson.numbers(i).ToString & ":" & Bperson.numbers(i).ToString)
Next
Console.Read()
End Sub
End Module
Re: Is this the proper way to deep clone a class?
To answer the question: No, there is no "proper way" to deep clone a class. If there was one proper way, it would be possible to create a compiler that did it right every time.
You can do a bit better than what you have, since you could use List.AddRange rather than iterating through each item, but that's a pretty minor quibble. You could also do things other than the MemberwiseClone, but whether or not they would be better is hard to say.
Re: Is this the proper way to deep clone a class?
The way he is doing it here is pretty much to only way to do a deep copy. Only difference is I'd use AddRange like you suggested and I'd call the method Clone not MakeACopy.
Re: Is this the proper way to deep clone a class?
I've never done this so can't provide code but I have seen code where you serialize it and then copy the binary stream. The benefit of doing it that way is that it should work on any serializable object without any knowledge of its structure. I believe it's quicker as well but, like I said, I've never done it so don't take my word for it. A quick google will find plenty of examples for you.
Re: Is this the proper way to deep clone a class?
Thanks guy, I think I"m finally getting the hang of this oop stuff.