Performing DeepCopy (clone) when connected to events

When you have an object that provides events, and you use the deep cloning (serialization) method to clone the object, how you do it when there are events on the object that is actually attached.

If my object declares an event but does not attach anything, the object can be cloned without problems.

BUT, if the object has attached events, then serialization is not performed. All related classes have the applicable Serializable attribute (except for Form1, which is used for testing).

So, in the following example, if I call Create(true), then Clone does not work (see the exception at the end).

If I call Create(false), then it works correctly

The sample code is contrived, but hopefully it will demonstrate what I'm trying to do.

private void Create(bool useEvent)
{
    mRab = new Rabbits();

    if (useEvent) mRab.Changed += new Rabbits.ChangedEventHandler(ChangedRabbits);

    Rabbit  r;
    r = new Rabbit();
    r.Monkeys.Add(new Monkey("Test"));
    mRab.Add(r);

    Rabbits r2;
    r2 = DeepClone(mRab);
}

public static T DeepClone<T>(T obj)
{
    using (var ms = new MemoryStream())
    {
        var f = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        f.Serialize(ms, obj);
        ms.Position = 0;
        return (T)f.Deserialize(ms);
    }
}

.   System.Runtime.Serialization.SerializationException: 'CSharpClonetest.Form1' Assembly 'CSharpClonetest, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null' .    System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers( RuntimeType)    System.Runtime.Serialization.FormatterServices.GetSerializableMembers( , StreamingContext)    System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()    System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter, ObjectWriter objectWriter)    System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter, ObjectWriter objectWriter)    System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)    System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize( , [] inHeaders, __BinaryWriter serWriter, Boolean fCheck)    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header [] headers, Boolean fCheck)    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph)    CSharpClonetest.Form1.DeepClone [T] (T obj) C:\Development\Spikes\TestDeepCloneEvent\CSharpClonetest\Form1.cs: 30

0
1

[field: NonSerialized] .

0

All Articles