Here’s an easy way of cloning an object (deep copy):
public T CloneObject<T>(T obj) where T:class { if (obj== null) return null; MemoryStream memstream = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(memstream, obj); memstream.Seek(0, SeekOrigin.Begin); T clone = (T)formatter.Deserialize(memstream); memstream.Close(); return clone; }
The requirement is of course that the object is serializable and marked with the [Serializable] attribute.