Posts Tagged deep copy

Deep Copy Array/ Collection/ etc using serialization

A useful snippet of code I used in a web services project a while ago which i just stumbled back across recently- allows you to make a deep copy of an array, where you would normally get a shallow copy, stopping you from manipulating it independently from the source. This gives you a completely fresh and separate copy. The original is serialised to a memory, then a new instance created from the serialised representation (so obviously if it’s an array of custom objects, those objects will need to be marked serializable)

OrderItem[] order_items_clone;
using( MemoryStream ms = new MemoryStream())
{
	System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
	formatter.Serialize(ms,order_items);
	ms.Seek(0 , SeekOrigin.Begin);
	order_items_clone = (OrderItem[])formatter.Deserialize(ms);
}

, , ,

No Comments