ILearnable .Net

June 22, 2006

String to Enum C#

Filed under: Uncategorized — andreakn @ 06:13

I found this little snippet on a blog by Mark Wagner’s blog,
and already this baby has saved me quite a bit of work, so I thought I’d post it also, btw. Marks blog can be found here

Convert a string to an enumerated (enum) value.

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.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: