Monday, October 25, 2010

Deep Copy in C#

Problem
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.

Solution
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);
    ms.Close();
    return retval;
}


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

to whatever file you put this in.
 


Reference  
1. http://weblogs.asp.net/gunnarpeipman/archive/2007/10/07/net-and-deep-copy.aspx 

No comments:

Post a Comment

There was an error in this gadget