Friday, August 28, 2009

I ran into the second person today who was confused on this concept, so I thought I'd post the answer here. For those of you who missed the question it is: "When I serialize an object, does it only serialize properties, or does it serialize the fields also?".

Well, the answer depends on how you serialize the object. For this post, I'm only going to talk about the BinaryFormatter. XmlSerializer and DataContractSerializer both work differently, reflecting on properties (for XmlSerializer) or properties and fields (for DataContractSerializer). Properties serialized with either the XmlSerializer or the DataContractSerializer will actually call any logic within the properties they're setting. Binary formatter does not. Here's some example code to prove that BinaryFormatter will leave your properties alone:

// another method to allow us to set the value. publicvoid SetValue(intvalue) { _value = value; } }}

The binary formatter establishes the actual "binary" representation of the object. The assumption with binary formatter is that, if the fields are all serialized, the properties will work as expected, because properties are nothing but fancy methods, basically. Thus, the BinaryFormatter only serializes fields, and never properties.