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);
    MessageBox.Show(“Uh oh!”);


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



One thought on “Convert a String to Enum

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s