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.

Leave a Reply to Anonymous Cancel reply

Please enter your comment!
Please enter your name here