Stas Petrov Stas Petrov - 1 month ago 26
C# Question

Custom Settings with ApplicationSettingsBase saving List of custom objects in C#

I am trying to use

ApplicationSettingsBase
with saving list of custom objects. Here is my application settings class:

internal class ApplicationSettings: ApplicationSettingsBase
{
[DefaultSettingValue(""), UserScopedSetting]
public List<MyAwesomeClass> MyObjects
{
get
{
try
{
return this["MyObjects"] as List<MyAwesomeClass>;
}
catch (SettingsPropertyNotFoundException)
{
return null;
}
}
}

public void Add(MyAwesomeClass val)
{
MyObjects.Add(val);
this["MyObjects"] = MyObjects;
}
}


Here is my custom class:

[Serializable]
public class MyAwesomeClass
{
public Guid Id { get; set; }
public string SomeStringProperty{ get; set; }
public bool SomeBooleanProperty{ get; set; }
}


And here is the usage:

_applicationSettings = new ApplicationSettings();
_applicationSettings.Add(new MyAwesomeClass {/*Some initial values*/});
_applicationSettings.Save();


But when application restarts _applicationSettings.MyObjects is always have zero count. I don't know why my list doesn't want saving. Can anybody help me with this? Thanks!

Answer

You need to decorate the property with [SettingsSerializeAs(SettingsSerializeAs.Binary)]:

[DefaultSettingValue(""), UserScopedSetting]
[SettingsSerializeAs(SettingsSerializeAs.Binary)]
public List<MyAwesomeClass> MyObjects

Application Settings Architecture » Setting Persistence » Settings Serialization
If you implement your own settings class, you can use the SettingsSerializeAsAttribute to mark a setting for either binary or custom serialization using the SettingsSerializeAs enumeration.