Thursday, July 30, 2009

How do you convert a string into an enum?

Yesterday I was writing a method which would pass me a string which I needed to return as an Enum type. I did it using switch but didn't like doing it that way.

I found the solution on Tim Sneath's blog. I like one liners :), using it replaced bunch of code, in my case 10 cases (could be more or less depending on how many Enum values you have).
Quote:
enum Colour
{
Red,
Green,
Blue
}

// ...
Colour c = (Colour) Enum.Parse(typeof(Colour), "Red", true);
Please visit Tim's blog post if you would like to read the full post.