Rob Kraft's Software Development Blog

Software Development Insights

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:
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:
[field: NonSerialized]
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:

   1:  [Test]
   2:  public void TheSizeOfOneModuleShouldNotExceed25000bytes()
   3:  {
   4:  var module = ModuleList.GetByModuleID(3);
   5:  long lBuffer = 0;
   6:  using (MemoryStream buffer = new MemoryStream())
   7:  {
   8:   BinaryFormatter formatter = new BinaryFormatter();
   9:   formatter.Serialize(buffer, module);
  10:   lBuffer += buffer.Length;
  11:  }
  12:  Assert.That(lBuffer, Is.LessThan(25000));
  13:  }

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: