views:

83

answers:

2

This is pretty closely related to another SO question.

Using the example below, could someone explain to me why adding a new List<Foo> where each of Foo's properties are explicitly set causes the ApplicationSettingsBase.Save() method to correctly store the data, whereas adding a new Foo to the list via a constructor (where the constructor sets the property values) does not work? Thanks!

public class Foo
{
    public Foo(string blah, string doh)
    {
        this.Blah = blah;
        this.Doh = doh;
    }

    public Foo() { }

    public string Blah { get; set; }
    public string Doh { get; set; }
}

public sealed class MySettings : ApplicationSettingsBase
{
    [UserScopedSetting]
    public List<Foo> MyFoos
    {
        get { return (List<Foo>)this["MyFoos"]; }
        set { this["MyFoos"] = value; }
    }
}

// Here's the question...
private void button1_Click(object sender, EventArgs e)
{
    MySettings mySettings = new MySettings();

    // Adding new Foo's to the list using this block of code doesn't work.
    List<Foo> theList = new List<Foo>()
    { 
        new Foo("doesn't","work")
    };

    // But using this block of code DOES work.
    List<Foo> theList = new List<Foo>()
    { 
        new Foo() {Blah = "DOES", Doh = "work"}
    };

   // NOTE: I never ran both the above code blocks simultaneously. I commented
   // one or the other out each time I ran the code so that `theList` was 
   // only created once.

    mySettings.MyFoos = theList;
    mySettings.Save();
}
A: 

This might be due to how you constructed your example. But using the given code, the "doesn't work" list is getting removed when you do the "does work" section. If you want both elements to be in theList at the end of the method, you can only have one new List<Foo>() call.

unholysampler
Actually, that example is just for explanatory purposes. I never ran the code with both blocks enabled at the same time. I'll edit my question for clarity.
Nick
I thought that might be the case. But it was worth a shot since I can't try code right now.
unholysampler
Yeah, thanks anyways. :) I should have clarified that point to start with.
Nick
A: 

I stumbled upon the answer while trying to clarify my question just now. If I supply a default constructor to the Foo class:

public Foo() { }

--leaving everything else the same--then the values of the class are correctly stored in the user.config file when ApplicationSettingsBase.Save() is executed. Weird.

Nick