Say I have a simple class like so
[Serializeable]
public class MyClass
{
public MyClass()
{
this.MyCollection = new List<int>();
}
public List<int> MyCollection { get; private set;}
}
If I try to deserialize this using XmlSerializer I get an error saying that MyCollection is readonly and cannot be assigned to. However I don't want to make the setter public as this can cause all kinds of problems if the user of the class assigns to it. FxCop rightly warns against this: Collection properties should be read only
However on the bottom of the page in the community added content is this:
XmlSerializer understands read-only collections Collection properties do not have to be read-write for the XmlSerializer to serialize and deserialize the contents correctly. The XmlSerializer will look for a method called Add on collection properties that implement ICollection or IEnumerable, and use that to populate the collection when deserializing an instance of the owner type.
However it just doesn't seem to be the case (as I get the InvalidOperationException). What am I able to do that obeys the best practice of keeping the property setter private while still allowing me to use the XmlSerializer?