Binary Serialization Notes in .Net 4.0
Posted by robkraft on December 5, 2011
I ran into a problem using binary serialization recently. Some of the objects that I was serializing were really large. By really large I mean that they were 2,000,000 bytes long instead of the expected 2,000 bytes long. I could not find a good source of information about binary serialization other than this fine article: http://www.diranieh.com/NETSerialization/BinarySerialization.htm
But even that article left we with questions. I ended up writing tests to find my answers. Here are my notes:
- In Binary Serialization, fields are serialized (in XML serialization they are not).
- Properties are serialized in both Binary and XML.
- In Binary Serialization, if you add a property for the field, the field and property are not both serialized (at least for simple properties).
- Static fields and properties are not serialized.
- Private fields ARE serialized in Binary Serialization.
- Properties without setters (ReadOnly properties) are not serialized.
- Make sure that you do not serialize events. That is what caused my objects to grow 1,000 times larger.
Make sure to apply this attribute to any events you define:
public new event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
We also wrote unit tests to make sure our objects did not experience unintended excessive growth in the future:
2: public void TheSizeOfOneModuleShouldNotExceed25000bytes()
4: var module = ModuleList.GetByModuleID(3);
5: long lBuffer = 0;
6: using (MemoryStream buffer = new MemoryStream())
8: BinaryFormatter formatter = new BinaryFormatter();
9: formatter.Serialize(buffer, module);
10: lBuffer += buffer.Length;
12: Assert.That(lBuffer, Is.LessThan(25000));