Daniel Mošmondor
Daniel Mošmondor

Reputation: 19966

BinaryFormatter picking up events

I have a storage class that has events on adding items to it. My form class handles the event. When I try to serialize it, formatter complains about form class not marked as serializable. Of course, I don't want to serialize it, however, i can't mark event as [NonSerialize] since it is not field...

What to do?

EDIT: Aditional info:

I tried both anonymous code block:

Storage.Instance.AllPartners.OnAdded +=
    new Partners.Added(delegate(Partner p) { 
        viewPartners.RefreshData(); 
    });

And event handler as member:

Storage.Instance.AllPartners.OnAdded += new Partners.Added(AllPartners_OnAdded);

void AllPartners_OnAdded(Partner partner)
{
    viewPartners.RefreshData();
}

Upvotes: 1

Views: 193

Answers (3)

Ian Ringrose
Ian Ringrose

Reputation: 51927

Make your event with NonSerializedAttribute. However to get this working, you need to tell the compiler to put the attribute on the backing field rather then the event it's self.

[field:NonSerialized()] 
public event ChangedEventHandler OnAdded;

Upvotes: 1

Patrik Svensson
Patrik Svensson

Reputation: 13854

Maybe you can implement the ISerializable interface.

public class MyClass : ISerializable
{
    private int m_shouldBeSerialized;
    private int m_willNotBeSerialized;

    protected MyClass(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("MyValue", m_shouldBeSerialized);
    }

    #region ISerializable Members

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        m_shouldBeSerialized = info.GetInt32("MyValue");
    }

    #endregion
}

Upvotes: 1

Mark Seemann
Mark Seemann

Reputation: 233257

Your storage class holds a reference to your form through the event, so the formatter attempts to serialize the form, since it is part of the state of the storage class.

Try to unsubscribe the form from the event before you serialize it, and then resubscribe immediately after serializing it.

Upvotes: 1

Related Questions