Tell me how to serialize a class with a collection of the type ObservableCollection`?

Trying to do on class Example .

 public class Animal { public string Sound { get; set; } } [Serializable] public class Example { public string Properties1 { get; set; } = "nothing"; public bool Properties2 { get; set; } public static ObservableCollection<Animal> MyCollection { get; set; } = new ObservableCollection<Animal>(); public Example() { MyCollection.Add(new Animal() { Sound = "Мяу"}); MyCollection.Add(new Animal() { Sound = "Гав" }); } } 

I serialize it, but only the properties are serialized:

 Example example = new Example(); XmlSerializer formatter = new XmlSerializer(typeof(Example)); using (FileStream fs = new FileStream("test.xml", FileMode.OpenOrCreate)) { formatter.Serialize(fs, example); } 
  • 3
    And why do you have a static collection? Her essna and not in the instance. Serialize the collection itself if only it is needed. - Monk
  • @Monk: Why not as an answer? - VladD
  • @VladD so maybe it is a typo, it is not clear - Monk
  • @Monk, No, not a typo :) Thank you! - trydex

1 answer 1

When an instance is serialized, static class properties are not serialized.

So, either MyCollection should be non-static, or the entire class should be redone to a singleton.