Dec 4, 2008

Serialization and Events

While trying to serialize a class today I learned that if a class has an event, and that event is subscribed to, .NET will attempt to serialize the class that is subscribing to the event. Seems like rather strange behavior to me but there's probably a good reason for it. Googling like mad turns up many references and many complicated solutions to this problem.  It also eventually turned up the correct simple one.  You're probably thinking, just use the [Nonserializable] attribute. Good idea but it won't work. An event is not a field. However, there is a modified version [field:Nonserializable]. This tells .NET to make the delegate behind the event non serializable. MSDN Magazine had a good article that mentions this back in 2004.
While I'm at it there is also a [property:NonSerializable] attribute but I don't think it works with auto properties. After all the "auto" kind of implies that you want all the default behavior, so you need to convert it back to a data backed property (CodeRush's "Create backing store" refactoring makes this fast and easy). 

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.