views:

207

answers:

1

Note that 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.


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.

+5  A: 

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

i.e.:

[field:NonSerializable]
public event EventHandler Roar;
frou