C# – How to deserialize an XML file into a class with a read only property

cnetxmlxml-serialization

I've got a class that I'm using as a settings class that is serialized into an XML file that administrators can then edit to change settings in the application. (The settings are a little more complex than the App.config allows for.)

I'm using the XmlSerializer class to deserialize the XML file, and I want it to be able to set the property class but I don't want other developers using the class/assembly to be able to set/change the property through code. Can I make this happen with the XmlSerializer class?

To add a few more details: This particular class is a Collection and according to FxCop the XmlSerializer class has special support for deserializing read-only collections, but I haven't been able to find any more information on it. The exact details on the rule this violates is:

Properties that return collections should be read-only so that users cannot entirely replace the backing store. Users can still modify the contents of the collection by calling relevant methods on the collection. Note that the XmlSerializer class has special support for deserializing read-only collections. See the XmlSerializer overview for more information.

This is exactly what I want, but how do it do it?

Edit: OK, I think I'm going a little crazy here. In my case, all I had to do was initialize the Collection object in the constructor and then remove the property setter. Then the XmlSerializable object actually knows to use the Add/AddRange and indexer properties in the Collection object. The following actually works!

public class MySettings
{
    private Collection<MySubSettings> _subSettings;
    public MySettings()
    {
       _subSettings = new Collection<MySubSettings>();
    }

    public Collection<MySubSettings> SubSettings
    {
         get { return _subSettings; }
    }
}

Best Answer

You have to use a mutable list type, like ArrayList (or IList IIRC).