How do I ignore event subscribers when serializing an object?
Asked Answered
M

1

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.

Murat answered 23/7, 2009 at 18:34 Comment(0)
M
30

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

i.e.:

[field: NonSerialized]
public event EventHandler Roar;
Murat answered 23/7, 2009 at 18:34 Comment(2)
Thanks. But why is that?Pindling
It is because System.NonSerializedAttribute has a constraint on it: it can only be applied to fields!Active

© 2022 - 2024 — McMap. All rights reserved.