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;
}
You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.
Serialization allows the developer to save the state of an object and re-create it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions such as: Sending the object to a remote application by using a web service.
It is not future-proof for small changes If you mark your classes as [Serializable] , then all the private data not marked as [NonSerialized] will get dumped. You have no control over the format of this data. If you change the name of a private variable, then your code will break.
Formatters. Binary Namespace. Contains the BinaryFormatter class, which can be used to serialize and deserialize objects in binary format.
"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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With