16

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.

xyz
  • 27,223
  • 29
  • 105
  • 125

1 Answers1

30

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

i.e.:

[field: NonSerialized]
public event EventHandler Roar;
coeing
  • 913
  • 1
  • 11
  • 9
xyz
  • 27,223
  • 29
  • 105
  • 125