Serialization and Events in C#
Join the DZone community and get the full member experience.
Join For FreeToday I had an interesting problem: I was trying to serialize and object using BinaryFormatter but it kept on failing because some class was not Serializable. I’ve double and triple checked my class and all of it’s inner properties and verified that indeed they were marked correctly.
The Problem
Looking closer at the exception I’ve noticed something – the problematic class that was causing me grief was not part of the class. In fact the problematic class was signed to an event of the class I was trying to serialize. SO I had the following code:var myObj = new SerializableClass(); var notSerializble = new NotSerializableClass(myObj); IFormatter formatter = new BinaryFormatter(); using (Stream stream = new MemoryStream()) { formatter.Serialize(stream, myObj); ... }
And the the class – NotSerializableClass was something like this:
public class NotSerializableClass { private SerializableClass myObj; public NotSerializableClass(SerializableClass myObj) { myObj.someEvent += HandleSomeEvent; ...
And so the fact that it was attached to the event from my perfectly serializable class caused the problem – the BinaryFormatter was trying to serialize it as well!
The Solution
Once I understood the problem the solution was simple – I’ve marked the event as field:NonSerialized and the problem was solved:[Serializable] public class SerializableClass { [field:NonSerialized] public event EventHandler someEvent; }Simple – as long as you know what to look for.
Published at DZone with permission of Dror Helper, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Scaling Site Reliability Engineering (SRE) Teams the Right Way
-
Managing Data Residency, the Demo
-
Tomorrow’s Cloud Today: Unpacking the Future of Cloud Computing
-
MLOps: Definition, Importance, and Implementation
Comments