Why adding custom objects to List<T> in ApplicationSettingsBase via constructor doesn't work?

Posted by BadNinja on Stack Overflow See other posts from Stack Overflow or by BadNinja
Published on 2010-05-05T17:55:30Z Indexed on 2010/05/05 17:58 UTC
Read the original article Hit count: 228

Filed under:
|

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 like this doesn't work.
    List<Foo> theList = new List<Foo>()
    { 
        new Foo("doesn't","work")
    };

    // But doing it like this DOES work.
    List<Foo> theList = new List<Foo>()
    { 
        new Foo() {Blah = "DOES", Doh = "work"}
    };

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about applicationsettingsbase