views:

45

answers:

3

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();
}
+1  A: 

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
}
Patrik
Good idea, but I would like cheaper solution...
Daniel Mošmondor
+1  A: 

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.

Mark Seemann
First fact is obvious, but I want to go cheaper then your solution - which is perfectly OK.
Daniel Mošmondor
+1  A: 

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;
Ian Ringrose
Does it work on .net 2.0?
Daniel Mošmondor
@Daniel, this has worked since .net 1.0
Ian Ringrose
This works great!
Daniel Mošmondor