Search code examples
c#settingsapp-configapplication-settings

How to save a custom collection to the application settings?


To follow up from this topic: How to save a List<string> on Settings.Default?

I am trying to do the same but with a custom collection. I've done the same as in the above posted link, but how can I do it for a list of objects?

For example if it is a List<FoodTypes> where FoodTypes has two properties - Food and Type.

FoodTypes:

Food    |    Type
------------------
Orange  |    Fruit
Lemon   |    Fruit
Pork    |    Meat  

The idea is that these types can be configured in future without getting them from the database or having to re-deploy the application. It's a Windows Service that will use them.

EDIT: I forgot to mention that I can add my class as a type of the setting, but then how do I add the Food and the Type to the Value column in the settings?

enter image description here

EDIT 2: The application doesn't have to change them or save new ones, it should only be able to read them from the config, so that it can compare the results which are returned from the database.


Solution

  • Assuming that the FoodType type is serializable (for instance, has the Serializable attribute).
    You can add the desired collection to the Settings.Designer.cs file:

    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Configuration.SettingsSerializeAs(global::System.Configuration.SettingsSerializeAs.Binary)]
    [global::System.Configuration.DefaultSettingValueAttribute("")]
    public List<FoodType> FoodTypes
    {
        get
        {
            return this["FoodTypes"] as List<FoodType>;
        }
        set
        {
            this["FoodTypes"] = value;
        }
    }
    

    The SettingsSerializeAs(SettingsSerializeAs.Binary) attribute value allows you to store everything in the settings.