Showing posts with label enum. Show all posts
Showing posts with label enum. Show all posts

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:

Wednesday, April 16, 2008

Enum Class

An enum is a constant that contains words to represent numbers basically. For example, your program might refer to days of the week with numbers 1 to 7, but to make your code more readable you can create an enum to show that 1 is equal to "Sunday". Here is an example: Before:
private void DoWork(int today)
{
    if (today == 1  today == 2)
        TakeABreak();
    else
        GetToWork();
}
After:
public enum Day
{
    Sunday = 1,
    Monday = 2,
    Tuesday = 3,
    Wednesday = 4,
    Thursday = 5,
    Friday = 6,
    Saturday = 7
}

private void DoWork(Day today)
{
    if (today == Day.Sunday  today == Day.Saturday)
        TakeABreak();
    else
        GetToWork();
}
But say you have an outside program that refers to days of week by actual names and not numbers, you can still use your enum:
private void DoWork(string today)
{
    if (today == Day.Sunday.ToString() 
        today == Day.Saturday.ToString())
        TakeABreak();
    else
        GetToWork();
}
More Info: MSDN: Enum Class