Over a million developers have joined DZone.

Serialization and Events in C#

DZone's Guide to

Serialization and Events in C#

Free Resource

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.

Published at DZone with permission of Dror Helper, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}