Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Can an Enum Value be saved as a Setting?

Tags:

c#

enums

settings

Can an enum value be saved as a setting, using the Properties.Settings.Default["MySetting"] syntax of C#? I tried to create a setting in my project's property pages, but only system classes appeared in the list of available types.

If it can be done, how do I do it? Thanks in advance for your help.

like image 295
David Veeneman Avatar asked Aug 25 '11 22:08

David Veeneman


2 Answers

just store it as an int and convert it when needed.

Properties.Settings.Default["MySetting"] = myEnumValue;

// and later 
var settingValue = Properties.Settings.Default["MySetting"];
MyEnum value = (MyEnum)settingValue;

If you feel the need you can use Enum.IsDefined(typeof(MyEnum), value) to make sure it is valid. You can also store a string value so that it is in a human-readable format in your config file:

Properties.Settings.Default["MySetting"] = myEnumValue.ToString();

// and later 
var settingValue = Properties.Settings.Default["MySetting"];
MyEnum value = (MyEnum)Enum.Parse( typeof(MyEnum), settingValue );
like image 200
Ed S. Avatar answered Sep 20 '22 13:09

Ed S.


It is an old post but I think this solution is worth publishing for whom may encounter the same issue.
Basically it consists in creating a new library to be referenced by the main project so that this library exposes the enum as a new type that can be selected from Properties.Settings.settings. In my case I want to enumerate levels of severity.

The new Library
Under your current solution, create a new empty Class Library with the code below:

namespace CustomTypes
{
    [Serializable]
    public enum Severity
    {
        INFO,
        WARNING,
        EXCEPTION,
        CRITICAL,
        NONE
    }
}

Reference the Library

  • Compile and reference the newly created library in all the projects that are going to use this type.
  • Now open your project's Properties => Settings.
    The new library may not be yet visible in the type DropDown list. If you don't see it, select Browse at the bottom of the DropDown and try to find the library.
    If it is still not visible, type the full path to the new type in the Selected Type field. (In this example, enter "CustomTypes.Severity" as shown below:

    enter image description here

    From now on, the new type should be visible and usable in Properties.Settings.settings.

    enter image description here
like image 35
Jean-François Avatar answered Sep 24 '22 13:09

Jean-François