Clone method

  • Thread starter Thread starter csharpula csharp
  • Start date Start date
C

csharpula csharp

Hello,
Have a basic question about Clone()
If I am using the clone method on some object ,are the Cloned object
properties going to change at every property change in original object?
Thanks!
 
It's your oject - you tell us!

Normally : no; however, I have once seen this type of behaviour in a
"facade"style wrapper - where the facade class held a reference to an
existing object and a few extension fields; when Clone()d, the reference (to
the base object) would be copied, so any updates to properties that were
actually pass-thru's to the base object would be reflected in both
instances, where-as updates to properties that only existed in the facade
would show as different in the two facades.

Marc
 
It depends on the clone method implementation.
There are two types of making a copy - deep and shalow.

First of all all value type memebers get their own copy, so changing such a
property or field in one of the objects doesn't affect the other.
Reference types are more interesting. If the clone method is implemented as
shallow copy that means only the reference is copied over the new object.,
thus both, the orginal and the clone, reference the same object in the heap.
In this case changes made via properties of one objects will be reflected by
the other. We have deep copy when not only the reference is copied, but the
whole refernced object is cloned - we have different object in the heap. In
this case all the changes are local for the objects.

As you can see it depends how the clone is implemented.
The object class provides MemberwiseClone method that does shalow copy. Also
when you assign one value type to another you get a shalow copy.
 
I assume you're talking about the ICloneable.Clone method. The is
answer is probably as long as the implementation actually makes a copy
of the member variables of the original object. There may be some
exceptions depending on whether the Clone implementation produces a
deep copy or a shallow copy.

The ICloneable interface never specified what kind of copy was to be
made. Microsoft would later regret the omission (see the Framework
Design Guidelines book) and has since mostly ignored its existence.
The problem is that interface didn't provide a behavioral contract. In
other words, you weren't sure what it was going to do exactly. As a
result the interface is mostly useless. In fact, Microsoft recommends
not using it at all (at least in public APIs).

Brian
 
Brian Gideon said:
The ICloneable interface never specified what kind of copy was to be
made.

One could say that the word itself specifies a deep copy. Cloned plants and
animals are deep copies - watering one clone doesn't water the others. :)
 
Back
Top