views:

636

answers:

1

I'm using Windows Forms and VS2008. I want to store an enum value in my application's settings file.

The settings editor in VS2008 only gives me a limited set of types. Amazingly, enums don't seem to be one of these types that are automatically supported - have I understood this correctly?

From reading up on the subject, it seems like I might need to write a TypeConverter class, to enable my enum to converted to string and vice versa. I've implemented this for my enum, and added the TypeConverter property to my enum, to indicate which converter class to use for that enum.

However, when I try to specify this in my settings file (in the 'Select a Type') dialog, it just says that my type is not defined, so I'm kind of stuck.

Can anyone explain to me how I store an enum in a Settings file in a Windows Forms app? It seems like such a crushingly simple (and commonly required) piece of functionality that I'm amazed it's not already supported, and that I seem to have to do so much work to get it to work (and for only one enum!).

Therefore I think I must be missing something, and it's actually really easy...

Let's say my enum looks like this:

namespace MyApp
{
    enum MyEnum
    {
        Yes,
        No
    }
}

...how do I store a value from this enum in my settings file? (And retrieve it, of course).

(Obviously I can just store a string or integer and interpret myself, but that seems pretty clunky, and I'd expect Windows Forms to handle this sort of thing more cleanly.)

+2  A: 

Enums are actually not that far removed from numeric types (default int) and can be used interchangably. I don't think it is clunky to cast back and forth and store the int. In fact only strings can be stored in the settings file. This does mean, by extension, anything that is serializable to string.

Another way would be to store the text value (so it's human editable) of the enum and parse it using Enum.Parse(type, string).

Robert Wagner
I prefer the text value over the integer. It's sort of true that only strings can be stored in the settings file, but actually anything that's serializable can be stored there.
Don Kirkby
I guess this is as good as gets with Windows Forms - I still think it's clunky that I have to handle enums myself, but thanks for the Enum.Parse() - with that and Enum.Format() I can do this directly with the settings string fairly simply.
Slacker
You don't even need Enum.Format. You can just ToString the value.
P Daddy
Ah yes, I did try ToString(), but intellisense told me it was obsolete and to use Enum.Format() - on checking, I've found it was telling me about a particular (different) overload of ToString(), so I now use ToString() and it works fine. Good, thought that was odd :-)
Slacker