.Net and Deep Copy

Some time ago I had to clone objects and .Net's shallow copy proved to be insufficient – it was necessary to use deep copy. No good tools are provided by .Net itself. If required, the object to be cloned must conform to the ICloneable interface and the Clone() method can be defined for the object. As the classes were not very numerous, but relatively bulky and complicated, there was no point in writing a Clone() method for all of them. I needed something else.

 

NB! This blog is moved to gunnarpeipman.com

Click here to go to article

6 Comments

  • I've been using a generic version of this for quite some time and I think the performance has been quite good.

    public static T DeepCopy(T item)
    {
    BinaryFormatter formatter = new BinaryFormatter();
    MemoryStream stream = new MemoryStream();

    formatter.Serialize(stream, item);

    stream.Seek(0, SeekOrigin.Begin);

    T result = (T)formatter.Deserialize(stream);

    stream.Close();

    return result;
    }

  • Hi guys!

    Thank you for your comments and examples. Your example are very useful on .Net versions starting from 2.0. The version I given here can also be used on earlier versions of .Net.

  • Greg, I cannot take your opinion as flame. I agree with you completely. It's not a good idea to use this methodics on larger data volumes or on more complex object trees.

  • Noone aware of the using command?

    public static T DeepClone(T item)
    {
    using (MemoryStream stream = new MemoryStream())
    {
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, item);
    stream.Location = 0;
    return (T) formatter.Deserialize(stream);
    }
    }

  • Hey Digimortal,

    I hear the sentement about lazy programing but, I wonder since there is no other way for me, what is better. I have been asked by my boss to do a publisher/subscriber patter that also passes data (kind of more publisher/subscriber mixed with medator) but due to multple subscribers reading a single object I have decided to give each subscriber a deep copy to do what they like with, this alows me to not worry about tracking whos where on the data or wether its still needed. so in this case needing to just make a deep copy of an object is usfull with out knowinwhat it is.

    Ps teh boss does nopt want teh subscriber or publisher taking any responsibility of notifying me whether or not teh object is needed still or what it is.

  • I was searching for deep copying a memorystream itself.
    How to do that?

Comments have been disabled for this content.