Property Won’t Serialize To XML Using System.Xml.Serialization.XmlSerializer

Ok I came across this problem just then and it makes sense but its annoying because I just spent the last few hours trying to figure out why. The problem that was posed is that a property I had on an object would not serialize to XML using the System.Xml.Serialization.XmlSerializer and I couldn’t see why.

At first I thought it might be because the property was a complex object so maybe I needed to explicitly define XML serializing attributes for the properties within the object, but that wasn’t the case. No errors were being thrown whatsoever – all that was happening was that the required property wasn’t being serialized.

I was staring at the property long and hard then realised it doesn’t have a ‘set’ method. Its at this point I then found out that you MUST have both a ‘get’ and ‘set’ method on a property in order for it to be serialized.

For those that may not see the reason, here is what I believe the reason is. If you are going to serialize an object, it would be fair to assume you will want to deserialize it too. In order to do this you would have to have write access to all data on the object that has been serialized. If a property has no ‘set’ method then why bother serializing it seeing it could never be deserialized back into that object. This reasoning does make alot of sense but without any warnings or exceptions its not obvious if you do make this mistake.

In summary, if your object is serializing with the exception of a few of the properties, make sure that your property has both a ‘get’ and ‘set’ method.

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