How do I make a deep copy of my own class? If possible I'd like some kind of method that can be used on all of my classes. There must be an easier way than to copy the classes field by field (i hope).
I have a class that - simplified - looks like this:
Class customer dim ID as integer dim Fname as string dim Lname as string end class ' Now I want to make a copy of an object of the class customer somwhere later in my code: dim cust1 as new customer dim cust2 as new customer cust1.id = 1 cust1.fname = "Jens" cust1.lname = "Brown" cust2 = cust1 cust2.lname = "Green" msgbox(cust1.lname) msgbox(cust2.lname)
The result here will be that both msgboxes will display "Green".
This is due to the fact that VB.NET does only copy the reference to the object when I write cust2 = cust1.
Copying the reference is like if you have a house and a sign that points out the house. The sign points at the house so you can find it - this is what a reference is, a sign that points out where in memory to find an object. Now, copying an object like cust2 = cust1 doesn't make a new house and a new sign, it only makes the sign cust2 point at the same house that the sign cust1 does.
A deep copy on the other hand makes a new object and copies all content from the original to the new copy. It's like building an exact copy of a house, putting it on a new lot and putting up a new sign that points to the house. (Explanation somewhat simplified here)
What if I want to make a copy of the object that cust1 holds (or points at)? What I need is a deep copy, some means to make the msgboxes in the above example display "Brown" and "Green" respectively.
PS: Edited to delete erraneous description of deep and shallow copy. Correct (hopefully) description below.
This post has been edited by jens: 07 December 2008 - 10:03 AM