views:

604

answers:

4

This is one i struggled with for ages so thought I'd document somewhere. (Apologies for asking and answering a question.)

(C# .net 2.0) I had a class that was being serialized by XmlSerializer, I added a new public property however it wasn't being included in the output XML.

It's not mentioned in the docs anywhere I could find, but public properties must have a set as well as a get to be serialized! I guess this is because it assumes that if you're going to serialize then you'll want to deserialize from the same file, so only serializes properties that have both a set and a get.

+1  A: 

As in the question: public properties must have both a get and a set to be serialized by XmlSerializer

Rory
+4  A: 

As mentioned, all properties must have both a getter and setter; annoyingly, this even includes lists. A typical collection property is read-only:

public List<Foo> Bar {get {...} }

However, for XmlSerializer you need to add a setter. Fortunately, DataContractSerializer rectifies this, but you don't have the same level of control over the xml layout (you can't use attributes, for example).

Other reasons it might not serialize:

  • it isn't public with get and set (or is readonly for a field)
  • it has a [DefaultValue] attribute, and is with that value
  • it has a public bool ShouldSerializeFoo() method that returned false
  • it has a public bool FooSpecified {get;set;} property that returned false
  • it is marked [XmlIgnore]

Any of these will cause it not to serialize

Marc Gravell
Although I do have some properties with just a get. They're also marked with XmlArray and XmlArrayItem attributes, so I guess that's why they get away with out a set.
Rory
In some cases, a property that returns a collection doesn't need a set, but it must be initialized in the constructor... It is the case for collections with no public constructor. But this behavior seems a bit inconsistent to me...
Thomas Levesque
I've never noticed that, thanks Thomas; I will investigate ;-p
Marc Gravell
+2  A: 
Cheeso
ah, you're right that it's there but wrong that you can't miss it :)
Rory
I read about a study once, that said people ignore headlines and call out boxes in articles, more often than they ignore the regular text. ?? Counter productive.
Cheeso
@Cheeso : that's right, I never look at the sponsored links in Google search results ;)
Thomas Levesque
come to think of it..... neither do I!
Cheeso
A: 

Also properties that return null are not serialized!

anonymous