The Pavement
Web Design and Application Develop

Converting a String to an Enum

July 31, 2007 09:35 by Shaun

I’ve come across the need to covert a string to an enum value on numerous projects in the past, each time I google the answer, implement it and then completely forget!  One solution I found was to construct a huge switch statement, this is obviously a bad idea.  For one it’s a waste of energy typing it all out plus it won’t deal with any future changes to the enum.  Instead have a look at the following code:

object Enum.Parse(System.Type enumType, string value, bool ignoreCase);

 Here’s  an example for a colour enum:

(Colour) Enum.Parse(typeof(Colour), "Green", true);

Easy huh!

Tags: Tags: ,
Categories: .NET
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag




Live preview

May 17. 2008 07:39

Gravatar