Saturday, January 17, 2009

Enum.Parse (String to Enum)

I recently wanted to convert a string held in a database to an enum. After a little digging I found Enum has a Parse method!
public enum Day
{
    Sunday = 1,
    Monday = 2,
    Tuesday = 3,
    Wednesday = 4,
    Thursday = 5,
    Friday = 6,
    Saturday = 7
}

Day daysEnum = (Day) Enum.Parse(typeof (Day), "monday", true);
// or even parse by number!
Day daysEnum = (Day) Enum.Parse(typeof (Day), "2", true);

Since Enum doesn't have a TryParse, you should wrap it in a try-catch. More Info: MSDN: