PDA

Click to See Complete Forum and Search --> : Clone method and updating


Tom Sawyer
Apr 18th, 2007, 04:27 PM
I have an object that I do some updates to and then need to compare against the original data to send out an email about changes.

One of the properties of this object is called ServiceRequests, which is a list populated via our Messaging System

The code I have is:

//This gets the info persisted to the db - ServiceRequests has a count of zero
Referral existingReferral = (Referral)RetrieveExistingEntity();

//This should create a new copy of the object that isn't affected by changes to the existingReferral object
Referral oldReferral = new Referral();
oldReferral = (Referral)existingReferral.Clone();

//This updates the existingReferral object with the ServiceRequests. There are no references to oldReferral in the method, so it shouldn't change
UpdateServiceRequestsFor(existingReferral);


After that, existingReferral has a list with 15 items in it, but so does oldReferral, when oldReferral should still have nothing in that property. As I understood the Clone() method, the objects have the same data in them, but different reference points on the heap, so changes to one should not cause changes to the other. Am I wrong about this and, if so, what do I need to do to make that happen?

jmcilhinney
Apr 18th, 2007, 09:44 PM
From the MSDN help topic for the IClonable.Clone method:Clone can be implemented either as a deep copy or a shallow copy. In a deep copy, all objects are duplicated; whereas, in a shallow copy, only the top-level objects are duplicated and the lower levels contain references.It's up to the author of the class how the Clone method is implemented, but a good developer will ALWAYS document which has been used.