I have a collection property that is of a custom type which inherits from BindingList. Currently, this property gets serialized via XmlSerializer even though it has no Setter. I
This is the documented behavior. It is explained, albeit unclearly, in Introducing XML Serialization:
XML serialization does not convert methods, indexers, private fields, or read-only properties (except read-only collections). To serialize all an object's fields and properties, both public and private, use the DataContractSerializer instead of XML serialization.
As you can see, get-only properties are in general not serialized -- except for read-only collections. But what does Microsoft mean by this? A collection is not a property after all.
What they mean is as follows:
XML serialization does not convert get-only properties or read-only fields (except get-only collection-valued properties with pre-initialized collections).
(Incidentally, this means that, if you add items to your collection in the containing type's constructor, then serialize and deserialize it, the default items will get duplicated. For an explanation of why, see XML Deserialization of collection property with code defaults. If I deserialize your Item
class I see this behavior.)
How does this apply in your case? Well, when you make your collection implement IXmlSerializable
, the serializer no longer interprets it as a collection; it interprets it as a black box. Thus its special rules for collections no longer apply. The property referring to your collection must now be read/write; XmlSerializer
will construct an instance itself, deserialize it, and set it into its parent just like any other non-collection property value.