Monday, June 4, 2007

Converting from Strings to Enum in C#

I'm not sure why I didn't know this, but here's how to convert from a string to an Enum in C#:

Using the Enum.Parse method, you can easily convert a string value to an enumerated value. Doing this requires the type of the enum and string value. Adding the true argument will cause the case to be ignored.

Using the following enum for this example:

private enum Aircraft
{
Beech,
Cessna,
Piper
}

You can easily convert the string to an enum value like this:

Aircraft air = (Aircraft) Enum.Parse(typeof(Aircraft), "Cessna", true);

Ideally you should wrap a try-catch around the Enum.Parse statement.

... Pulled this from http://blogs.crsw.com/mark/archive/2005/04/07/832.aspx

No comments: