| Adam Vandenberg ( @ 2005-09-19 09:34:00 |
| Entry tags: | c#, dotnet, programming |
HowTo: Mark an event as "NonSerialized" in C#
This may be common knowledge, but took far too long to figure out (as nothing helpful came up on a Google search.)
When using object serialization in .NET, the default serialization behavior is to serialize event handlers (and the objects which are listening) which leads to a couple of problems.
1) You're serializing out a larger object graph than you potentially need, since (in our case) we don't want events on the other side of the wire, just the object data.
2) Chances are the objects handling events aren't serializable, or have members which aren't serializable.
You can't mark a public Event as [NonSerialized] because there's some compiler magic going on behind the scenes, but you can mark a private Event, and provide a public event with add/remove accessors:
[NonSerialized]
private EventHandler myEvent;
public event EventHandler MyEvent
{
add { myEvent+= value; }
remove { myEvent-= value; }
} Gross and non-obvious; the compiler should be smart enough to do this for you, but I guess I'll just have to see what C# 2.0 lets you do.