We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
Lately I have been playing around with serializing and deserializing of objects, and I stumbled upon a very weird behavior. I was trying to serialize a certain object that was implementing the INotifyPropertyChanged Interface. I marked the object as [Serializable] and used the following method to serialize it:
Only to get a runtime Exception saying that The PropertyChanged event could not be serialized.
I bet you know that serializing is Recursive, but I have found out another interesting thing about it. Once I solved the problem I prepared a small code example to demonstrate the problem, but when I ran the code I got no exception. That really got me investigating. As I said, Serialization is Recursive, If you have declared an event, and an object has registered to that event, the serialization process will try and serialize that object! Beware!!!
Take the following code for example:
It took me some time to understand that by writing the following code:
This can be serialized with no special problems.
Adding the following code in the UI will start the problems:
Do you see why?
By using the “Binding” expression I am registering to the PropertyChanged event and when serializing the WPF Window will be serialized also, and surprise surprise, it is not Serializable. It took me some time to see this “Hidden” event registration.
What to do? We have to mark the Event so it wont be Serializable. The problem is that The following attribute: [NonSerialized] does not work for it. The application still crashes. You will have to use the following [Field:NonSerialized] and only then will the Binary Formatter will ignore the Event’s registered objects.
Definitely an Error that is hard to find for the first time…
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd