Converting Strings to Enums

Enums are great. They provide additional type safety and make code more readable.

Converting enums to strings is trivial. Converting strings to enums is not as straightforward...so here is a code snippet:

    // This enum is in the .Net frameworkpublic 
    enum DayOfWeek
    {    
        Sunday = 0,    
        Monday = 1,   
        Tuesday = 2,   
        Wednesday = 3,    
        Thursday = 4,   
        Friday = 5,   
        Saturday = 6,
    } 
 
    protected void Button1_Click(object sender, EventArgs e)
    {    
        // converting enums to strings is easy    
        String WhatDayItIs = DayOfWeek.Monday.ToString();     
 
        // converting strings to enums is a bit more work    
        DayOfWeek WhatDayItIsDOW;
 
        if (Enum.IsDefined(typeof(DayOfWeek), WhatDayItIs)) 
            WhatDayItIsDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), WhatDayItIs);
    }
 

I hope you find this information useful.

Steve Wellens


2 Comments

  • That is a good example, however, I would go one step further and first check that value is defined. If the string value is not a defined Enum, then the Enum.Parse will throw an exception.

    DayOfWeek WhatDayItIsDOW;
    if (Enum.IsDefined(typeof(DayOfWeek), WhatDayItIs )) {
    WhatDayItIsDOW = (DayOfWeek) Enum.Parse(typeof(DayOfWeek), WhatDayItIs , true);
    } else {
    //Error: do something
    }

  • Elijah Manor,

    That is an excellent suggestion. I will update the example. (I had looked for Enum.TryParse(...) but there was none.)

    Thanks.

Comments have been disabled for this content.