Performing a DeepCopy(clone) when Events are Attached


When you have an object that provides events and you use a deepclone (serialisation) approach to cloning the object, how do you do it when there are events on the object that are actually attached.

If my object declares an event, but nothing is attached then object can be cloned without issue.

BUT if the object has had events attached, then the serialisation fails. All the associated classes have their Serializable attribute applied (except the Form1, which is being used for testing).

So in the following example, if i call Create(true) then the Clone fails (see exception at the end).

If I call Create(false) then it works properly

The example 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); } }

The exception when Cloning when the event is attached. System.Runtime.Serialization.SerializationException: Type 'CSharpClonetest.Form1' in Assembly 'CSharpClonetest, Version=, Culture=neutral, PublicKeyToken=null' is not marked as serializable. at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter) at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter) at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo) at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph) at CSharpClonetest.Form1.DeepClone[T](T obj) in C:\Development\Spikes\TestDeepCloneEvent\CSharpClonetest\Form1.cs:line 30


Add [field: NonSerialized] to the event declaration.


  • Conceptual Modelling - Is my drawing correct ?
  • Playback a file to both sites of a call by DTMF request
  • How to declare one-to-many using Fluent API without changing the model?
  • Plotly: Bar and pie charts side by side
  • Angular2 + Typescript1.5 Routing
  • org.springframework.cloud.task.launcher.TaskLauncherSink required a bean of type 'org.springfra
  • Toggle a blank screen in vim, to see through transparent window
  • Spring RabbitTemplate is not creating dead letter queue with TTL
  • SSH, run process and then ignore the output
  • Android Studio - MonkeyTalk Integration - Issues
  • Python RegEx, match words in string and get count
  • Boot EBS volume from Bamboo instance
  • IIS and ISAPI-WSGI = very slow
  • Why is my SqlPackage DeployReport returning an empty report?
  • How to combine two lists together?
  • Is there a parser equivalent of 'fragment' marking in ANTLR4?
  • Inversing an interpolation of rotation
  • Build Successful but not running on simulator
  • how to do an event when i swipe from fragment to the other
  • Display issues when we change from one jquery mobile page to another in firefox
  • Deselecting radio buttons while keeping the View Model in synch
  • JFileChooser in front of fullscreen Swing application
  • HTML download movie download link
  • How to draw moving and Running sine wave chart using JFree chart in java?
  • Possible to stop flickering java tooltip in heavyweight mode?
  • sending/ receiving email in Java
  • JSON with duplicate key names losing information when parsed
  • Eraser for UIBezierPath
  • Jquery - Jquery Wysiwyg return html as a string
  • Suggestions to manage Login/Logout transitions
  • Angular 2 constructor injection vs direct access
  • Java static initializers and reflection
  • Exception on Android 4.0 `android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode)`
  • Android Google Maps API OnLocationChanged only called once
  • unknown Exception android
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • failed to connect to specific WiFi in android programmatically
  • UserPrincipal.Current returns apppool on IIS
  • How can I use threading to 'tick' a timer to be accessed by other threads?