c# – Десериализация ObservableCollection


There is such a class with a collection:

public class Animal
    public string Sound { get; set; }

public class Example
    public ObservableCollection<Animal> animals { get; set; } = new ObservableCollection<Animal>()
        new Animal() {Sound = "Гав"},
        new Animal() {Sound = "Мяу"},
        new Animal() {Sound = "Кря"}

    public Example()


Serialize to XML and everything goes fine. The file looks like this:

<?xml version="1.0"?>
<Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

But after deserialization, the collection contains 6 elements, instead of 3. As I understand it, this is due to the fact that when creating an instance of a class, the initial 3 elements are added to the collection thanks to the constructor, and then 3 more are added during deserialization.

How to make sure that there is nothing superfluous in the collection after deserialization?


There is a straightforward solution:

  1. Create a separate constructor that receives the XML path as input. We load XML into memory and go through it with handles to perform correct initialization.
  2. Make an additional named constructor for the user and add logic to populate the tool collection. Users will create an object with this constructor and there will be initialization of the collection with initial values, and the deserializer will use the default constructor.

Maybe there are some other interesting solutions, but these are the fastest in implementation.

Scroll to Top