views:

282

answers:

2

I have a simple class that is marked as Serializable, and it happens to have an event. I tried to mark the event member as NonSerialized, however the compiler complains. Yet when I go to serialize the class instance, the BinaryFormatter throws an exception that the event is non serializable. Does that mean you can't serialize classes that have events? If so, then the compiler should say so up front.

Stream file = File.Open("f", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();

object obj = null;
try
{
    obj = bf.Deserialize(file);
}
catch (System.Runtime.Serialization.SerializationException e)
{
    MessageBox.Show("De-Serialization failed : {0}", e.Message);
}
file.Close();

System.Collections.ArrayList nodeList = obj as System.Collections.ArrayList;

foreach (TreeNode node in nodeList)
{
    treeView.Nodes.Add(node);
}

Fails to work on the following class:

[Serializable()]
class Simple
{
    private int myInt;
    private string myString;
    public event SomeOtherEventDefinedElsewhere TheEvent;

}

+1  A: 

"In the case of events, you must also add the field attribute qualifier when applying the NonSerialized attribute so that the attribute is applied to the underlying delegate rather than to the event itself" Advanced Serialization - MSDN


Prefix the NonSerializedAttribute with field

[field:NonSerialized]
public event MyEventHandler MyEvent;
Asad Butt
I tried that however it didn't change anything. I still get the exception. It would be very odd that there's no way to dissuade the formatter from trying to serialize this. Any other suggestions?
Rhubarb
A: 

It is important to remember that the attribute is [Field:NonSerialized] is applied to the delegates, not the events, case sensitive by the way, then implement a ISerializable object, and using reflection, iterate through the class that you are serializing, looking for the event handler, and unsubscribe the events first prior to serializing. Then when doing the deserializing, you can then wire up the events if necessary automatically on deserializing...

Hope this helps, Best regards, Tom.

tommieb75
Are you sure? Looks like field should be lower case 'f'. What is the point of having non serialized if I have to go and unsubscribe the events?
Rhubarb
@rhubarb@ You are freeing up the delegate by iterating through the list of listeners the delegates has or events, if you dont' the serializer will recurse through them...
tommieb75
Well why do we need to free the listeners if the event is marked as non serializable? Isn't that a contradiction?
Rhubarb