A system at work stores big object graphs in the database as varbinary(MAX). To do this, the BinaryFormatter class is used. When my new version of the system was installed, the objects would be retrieved out of the database as normal, but after deserialization, they were empty – all properties had default values (i.e. null for reference types, 0 for ints, etc). This was a bit of mystery, as no exceptions were being thrown, and all I thought I’d done was add a new property to the bottom of one of the classes.

I realised I’d also employed my anal side to change the names of the private backing fields for the properties. Might as well try out the code plugin here, so… I changed this:

private int SomePropertyField;

public int SomeProperty {
   get { return SomePropertyField; }
   set { SomePropertyField = value; }

to this:

private int someProperty;

public int SomeProperty {
   get { return someProperty; }
   set { someProperty = value; }

I was under the mad impression that changing private fields was ok. Not so when using binary serialization – the entire oject graph is serialized, including both public and private members.

If you’re going to use binary serialization, it’s probably wise to prevent any private fields from being serialized, like so:

private int someProperty;

If this wasn’t considered though, it’s too late. It seems like using binary serialization is painting yourself into a corner. Once you’re saving and retrieving binary, it’s difficult to change the format, apart from adding fields or changing enumerations. Adding the [NonSerializable] attribute after you’ve started saving stuff away will break compatibility, so you’re pretty stuck. This seems to destroy the whole concept of using public properties with private backing fields – you’re supposed to be able to keep a consistent public interface whilst maintaining control over the internal implementation.

From my brief foray into the world of binary serialization, I’d say it’s best to thoroughly plan out exactly what you need to be serialized, or it will be too late to change anything. Either that or don’t bother and save a big headache.

No Comment.

Add Your Comment