Adam Vandenberg ([info]piehead) wrote,
@ 2005-09-19 09:34:00
Previous Entry  Add to memories!  Tell a Friend  Next Entry
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.



(1 comment) - (Post a new comment)

Or....
(Anonymous)
2006-12-25 05:43 am UTC (link)
Or... use [field:NonSerialized] on your standard event.

public delegate void EventHandler();
[field: NonSerialized]
public event EventHandler Event;

(Reply to this)


(1 comment) - (Post a new comment)

Create an Account
Forgot your login or password?
Login w/ OpenID
English • Español • Deutsch • Русский…