WPF C# Deserialize an observable collection <string> with XmlSerializer adds extra items -


i wish save , load class (measconsettings) contains observablecollection<string> problem list initialized in constructor when following:

xmlserializer serializer = new xmlserializer(typeof(measconsettings)); 

a list created items 1 2 3 4. saves fine, on loading side goes wrong:

measconsettings loadedsettings = (measconsettings)serializer.deserialize(stream); 

it starts initialized list , adds loaded list items instead of overwriting them result list items 1 2 3 4 1 2 3 4.

obviously solution remove initialization constructor shown in topic:deserializing list xmlserializer causing items if file not contain list (e.g. previous version of saved file), if remove initialization , there no list present in saved file, there no items in list. not acceptable so:

is there proper way load observable collection initialization in constructor without ending duplicate items?

or

is there proper way check if saved file contains parameters?

if remove initialization , there no list present in saved file, there no items in list. not acceptable

then handle special case in initialization.

public void init() {     if (this.list == null)     {         // initialize list     } } 

from there, have call init method everytime create measconsettings object (either calling constructor or using deserializer).

that said, i'm not overly fond of initialization methods, lack visibility , fellow developer can forget call them. alternative, can use getter:

private list<int> list;  public list<int> list {         {         if (this.list == null)         {             this.list = new list<int> { 1, 2, 3, 4 };         }          return this.list;     }      set     {         this.list = value;     } } 

note: code isn't thread-safe.


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -