Monday, October 25, 2010

Deep Copy in C#

If a modifiable object is ever accessed by multiple users, then you need to do a deep copy to make sure they aren't using the same object.

For example, if you cache an object.

Use this DeepCopy method:
public object DeepCopy(object obj)
    MemoryStream ms = new MemoryStream();
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms, obj);    

    object retval;
    ms.Seek(0, SeekOrigin.Begin);
    retval = bf.Deserialize(ms);
    return retval;

Note: You'll need to add 
"using System.IO;
using System.Runtime.Serialization.Formatters.Binary;"

to whatever file you put this in.


No comments:

Post a Comment

There was an error in this gadget