a developer's notes – a semi-technical web development BLOG

September 5, 2011

Two ways to get an Enum with a string

Filed under: C# — Duy Nguyen @ 2:33 pm
Tags: , , ,

Two ways to get an Enum. Consider the following Enum:

 public enum MyEnumType
    {
        Default = 0,
        First,
        Second,
        Third,
    }

How to get an Enum type from a string equivalent to the Enum value?

(MyEnumType)Enum.ToObject(typeof(MyEnumType), Convert.ToInt16('1'));

// Gives you MyEnumType.First

How to get an Enum type from a string equivalent to the Enum name?

(MyEnumType)Enum.Parse(typeof(MyEnumType), 'Second', true); 

//passing in true as the third parameter makes it not case-sensitive
// Gives you MyEnumType.Second

How to get a value from an Enum?

int enumVal = (int)MyEnumType;
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: