Saturday, September 23, 2006

".Net 2 Solution to Serialization of Objects that Raise Events"

Rockford Lhotka - .NET 2.0 solution to serialization of objects that raise events

"In .NET 1.x there's a problem serializing objects that raise events when those events are handled by a non-serializable object (like a Windows Form). In .NET 2.0 there's at least one workaround in the form of Event Accessors.

The issue in question is as follows.

I have a serializable object, say Customer. It raises an event, say NameChanged. A Windows Form handles that event, which means that behind the scenes there's a delegate reference from the Customer object to the Form. This delegate that is behind the event is called a backing field. It is the field that backs up the event and actually makes it work.

When you try to serialize the Customer object using the BinaryFormatter or SoapFormatter, the serialization automatically attempts to serialize any objects referenced by Customer - including the Windows Form. Of course Windows Form objects are not serializable, so serialization fails and throws a runtime exception.

...

The end result is that we have declared an event that doesn’t cause problems with serialization, even if the target of the event isn’t serializable.

..."

Sigh... I SO could have used this just a few weeks ago.

(via del.icio.us/tag/.net - del.icio.us/burn_process/.net/)

No comments: