Convert a String to Enum

To convert enum to string is very easy… just add .ToString() at the end of an enum variable. But to convert a string into an enum variable is another story. It’s very easy but it’s one of those things that could never find when searching for it, but when found it seems obvious.

You just have to make the following:

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

The next code shows an example how to make this simple conversion:

enum Colour { Red, Green, Blue } 

// …
Colour c = (Colour) Enum.Parse(typeof(Colour), “Red”, true);
Console.WriteLine(“Colour Value: {0}”, c.ToString());

// Picking an invalid colour throws an ArgumentException. To
// avoid this, call Enum.IsDefined() first, as follows:

string nonColour = “Polkadot”;if (Enum.IsDefined(typeof(Colour), nonColour))
    c = (Colour) Enum.Parse(typeof(Colour), nonColour, true);
else
    MessageBox.Show(“Uh oh!”);

 

And that’s it. You have successfully converted your string into an enum! Happy Converting! 😀

resources: http://blogs.msdn.com/tims/archive/2004/04/02/106310.aspx

Categories

One Response

Leave a Reply

Your email address will not be published. Required fields are marked *