Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ignore event subscribers when serializing an object?

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.

like image 628
xyz Avatar asked Jul 23 '09 18:07

xyz


People also ask

How do I prevent some data from getting serialized?

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.

What attribute is used to prevent a public field from being serialized?

When using the BinaryFormatter or SoapFormatter classes to serialize an object, use the NonSerializedAttribute attribute to prevent a field from being serialized.

What does it mean to serialize an object c#?

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.


1 Answers

You have to include "field:" as part of the [NonSerialized] attribute on the event.

i.e.:

[field: NonSerialized]
public event EventHandler Roar;
like image 200
xyz Avatar answered Sep 20 '22 21:09

xyz