Dictionary XML Serialization

Viewed 11759

I have a class with a dictionary attribute I want to serialize. I've read that serializing a dictionary isn't directly possible so I serialize/deserialize a list I then transform to a dictionary. It works, but i would like to know if there is a proper way to do this.

[Serializable]
public class Album
{

    private List<Photo> photos = new List<Photo>();
    [XmlArray]
    public List<Photo> Photos
    {
        get { return photos; }
        set
        {
            photos = value;
        }
    }

    private Dictionary<string, Photo> dicoPhotos = new Dictionary<string, Photo>();
    [XmlIgnore]
    public Dictionary<string, Photo> DicoPhotos
    {
        get { return dicoPhotos; }
        set { dicoPhotos = value; }
    }


    public void fillPhotosDictionnary()
    {
        this.dicoPhotos = this.photos.ToDictionary(p => p.Nom, p => p);
    }
}

I've tried to fill the dictionary in the Photo's setter, but it doesn't work and I can't figure out why.

4 Answers
Related