TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Deep Copying, Serialization, and Fun With Attributes

I found an interesting solution for creating a deep copy of an object in .NET using serialization. Eager to test it out, I wrote the following code in my Foo class:

public Foo Copy()

{

    Foo copy = null;

    using(MemoryStream memStream = new MemoryStream())

    {

        BinaryFormatter formatter = new BinaryFormatter();

        formatter.Serialize(memStream, this);

        memStream.Seek(0, SeekOrigin.Begin);

        copy = (Foo) formatter.Deserialize(memStream);

    }

    return copy;

}


Of course, in order to make this work, I had to use the [Serializable] attribute on Foo plus the classes it utilized internally. Alas, upon trying to create a copy with my cool new method, I got a nice little exception, ""Serialization will not deserialize delegates to non-public methods." At first I just assumed that the "free serialization" I get from the framework via [Serializable] attribute would have to be replaced with implementing the ISerializable attribute and writing my "roll-your-own" serialization code with the GetObjectData method. It turns out that the exception was being thrown because of a public event field that I had exposed in class contained within Foo named Bar. (NOTE: I'm changing the names of my classes to "protect the innocent")

public delegate void BarAddedHandler(Bar bar);

public event BarAddedHandler BarAdded;


It turns out that you can simply apply the [NonSerialized] attribute using the "field:" qualifier to avoid this problem.
 

[field:NonSerialized]

public event BarAddedHandler BarAdded;

Anyone have a better idea for handling either the deep copy problem or the serialization issue? I'm always looking for good (and better) ideas, so let me know what you think.  :-)


Digg!

posted on Tuesday, February 08, 2005 12:29 PM

Feedback

# re: Deep Copying, Serialization, and Fun With Attributes 4/27/2005 7:35 AM Korhan Güçoğlu

I owe you a lot.....
Thank you very much....

# re: Deep Copying, Serialization, and Fun With Attributes 6/2/2006 2:37 PM Anonymous

Thanks, this works great. I was worried I'd have to implement ISerializable

# re: Deep Copying, Serialization, and Fun With Attributes 6/22/2006 12:21 PM CanuckFromBaku

It works great if you don't care that the event won't work after deserializing your object. But if you have an object hierarchy where some objects fire events to notify others, then those lines of communication will be severed after you deserialize the hierarchy because the events will no longer be hooked to their handlers. :(

# re: Deep Copying, Serialization, and Fun With Attributes 6/22/2006 1:39 PM Sean Chase

Yeah, it's hard to serialize pointers. :-)