Serialization and events in C#

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.

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:

public class SerializableClass
    public event EventHandler someEvent;

Simple – as long as you know what to look for.

Labels: , ,