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;

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Create a free website or blog at WordPress.com.