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:

[Serializable]
public class SerializableClass
{
[field:NonSerialized]
public event EventHandler someEvent;
}

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

One thought on “Serialization and events in C#”

  1. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s