Steve Wellens

Programming in the .Net environment

Sponsors

Links

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


Posted: Oct 26 2008, 11:00 AM by SGWellens | with 2 comment(s)
Filed under: , ,

Comments

Elijah Manor said:

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

}

# October 27, 2008 2:13 AM

SGWellens said:

Elijah Manor,

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

Thanks.

# October 27, 2008 10:00 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)