Today 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.
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())
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!
Once I understood the problem the solution was simple – I’ve marked the event as field:NonSerialized and the problem was solved:
public class SerializableClass
public event EventHandler someEvent;
Simple – as long as you know what to look for.
One thought on “Serialization and events in C#”
I wonder what your use case is for using BinaryFormatter in the first place. It is slow, taking a lot of space, and has to deserialize to the exact same type (from the exact same assembly) in the other side. There are many better alternatives these days in .NET land