Can I deep clone a c# object not tagged ICloneable or Serializable?
FYI Interfaces marked as ICloneable
are not necessarily deep copied. It is up to the implementer to implement ICloneable
and there is no guarantee they will have cloned it.
You say the object doesn't implement ISerializable
but does it have the Serializable
attribute?
Creating a deep copy via binary serialization is probably one of the easiest methods I know of, since you can clone any complex graph in 3-5 lines of code. Another option would be the XmlSerializer
if the object can be XmlSerialized
(You don't specify any attributes for serialization or implement interfaces however if there is an IDictionary
interface your hosed.
Outside of that I can't really think of anything. If all the data is publicly accessible you could do your own cloning routine. If its not you can still clone it by using reflection to get set the private data.
The "deep" is the tricky bit. For a shallow copy, you could use reflection to copy the fields (assuming none are readonly, which is a big assumption) - but it would be very hard to get this to work (automatically) otherwise.
The other option is to provide the serializer yourself (and serialize to deep-clone) - a "serialization surrogate". Here's a VB example.