C#: Can an Enum Value be saved as a Setting?
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 );
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 thetype
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 theSelected Type
field. (In this example, enter "CustomTypes.Severity" as shown below:
From now on, the new type should be visible and usable in Properties.Settings.settings.