When the following class is serialized with a BinaryFormatter
, any objects subscribing to the Roar
event will also be serialized, since references to those objects are held by the EventHandler delegate.
[Serializable]
public class Lion
{
public event EventHandler Roar;
public string Name { get; set; }
public float Fluffiness { get; set; }
public Lion(string name, float fluffiness)
{
Name = name;
Fluffiness = fluffiness;
}
public void Poke()
{
Roar(); // Could be null, etc..
}
}
How would you stop event subscribers being serialized as part of the object graph starting with a Lion?
Putting the [NonSerializable]
attribute on the event
will not compile.
Note: I'm answering my own question since I think it might be useful to have the information on the site!
FAQ: It's also perfectly fine to ask and answer your own question, but pretend you're on Jeopardy: phrase it in the form of a question.
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.
When using the BinaryFormatter or SoapFormatter classes to serialize an object, use the NonSerializedAttribute attribute to prevent a field from being serialized.
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
You have to include "field:
" as part of the [NonSerialized]
attribute on the event
.
i.e.:
[field: NonSerialized]
public event EventHandler Roar;
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