Clone an object in an integration scenario is a quite common operation we need to do,  many time integrate could means move values objects, transform data between references and so on, many time is very useful to be able to duplicate our objects and “data containers”.

Well, one of the common approach, is using the MemberwiseClone method, it create a shallow copy of the object and we can use the clone as “copy” but it doesn’t work with any scenario, below the exact limits:

The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.

Essentially all the object reference are still working and is going to be complicate abstract the value object for different clones / values.

Another option is to implement the iClonable interface and use the MemberwiseClone , this is a very god option to control in deep the cloning and we will be sure to recreate a new one clone, obbiovusly we need to write all the code to replicate ore object in our Clone() method and use theMemberwiseClone where we need.

An interesting tip I like to use is serializing the object, we can use any serialization pattern the important thing is just serialize the object,for example, a method to serialize an object to a byte array and on from a byte array to byte array as below.

public static byte[] ObjectToByteArray(object objectData)
{
if (objectData == null)
return null;
var binaryFormatter = new BinaryFormatter();
var memoryStream = new MemoryStream();
binaryFormatter.Serialize(memoryStream, objectData);
return memoryStream.ToArray();
}

public static object ByteArrayToObject(byte[] arrayBytes)
{
if (arrayBytes == null) return Encoding.UTF8.GetBytes(string.Empty);
var memoryStream = new MemoryStream();
var binaryFormatter = new BinaryFormatter();
memoryStream.Write(arrayBytes, 0, arrayBytes.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
var obj = binaryFormatter.Deserialize(memoryStream);
return obj;
}

and simply serializing the object to clone it.

byte[] byteobj = SerializationEngine.ObjectToByteArray(objecttoclone);
var newobjectclone = SerializationEngine.ByteArrayToObject(byteobj);

it works perfectly and it is very simple to implement, logically the object need to be serializable.

7 COMMENTS

    • Hi Ivan, the serialization using binary serialization or what I like to call Deep Cloning, is the best way for me to be sure to clone an object in deep and easy way, I tried using the classic methods as MemberwiseClone and so on but it doesn’t work well in complex structs in memory and the IClone (able) interface approach requires you to manage your internal serialization in the object and this is something that I don’t want to do because I don’t want to use any other preventive approach, about the performances the binary formatter is not so bad considering that you can serialized in deep and without the same sizing and contract restrictions as xml or json, for pure messaging purposing the Json is a good compromise (performances/sizing/Data Type Contract) and I think in extreme the MsgPack is the best one but this is not the purpose to clone an object but messaging.

  1. ICloneable is there for a reason, there is no magic way to deep clone objects as it heavily depends what the object is. For example one of your classes has a reference to a database connection, you serialise/deserialise it and it stops working. Or it holds a reference to an expensive data structure where cloning takes ages. Or the actual business logic dictates that one of the members MUST BE a singleton reference and doing so you’ve just broke it. I can think of millions of reasons.

    Another thing is serialisation is really slow, even binary one! Cloning even a thousand of objects takes ages comparing to a simple ICloneable implementation. And we solve it by making up scaling solutions whereas all we need is a correct architecture and common sense!

Leave a Reply to Nino Crudele Cancel reply

Please enter your comment!
Please enter your name here