.Net Tips — converting between Enum and string

If you’re read­ing this then you should already know what an enum is in C# and that the under­ly­ing type of an enum ele­ment is int and you can con­vert between int and enum using cast­ing:

public enum MyColours { Red, Green, Blue}
MyColours red = MyColours.Red;
int redInt = (int) red; // this return 0, the default value for the first element in an enum
MyColours redFromInt = (MyColours) redInt; // this returns MyColours.Red

How­ev­er, some­times you want to con­vert an enum ele­ment to and from strings instead of ints because:

  1. they’re more human­ly read­able
  2. chang­ing the order of the ele­ments won’t break your appli­ca­tion

If you have used an enum val­ue as part of a string.Format call like this:

string.Format("Is your favourite colour [{0}]?", MyColours.Green);

Then you’ll see that the string lit­er­al “Green” is dis­played rather than the under­ly­ing inte­ger, because the default ToString method has tak­en care of the enum to string con­ver­sion for you already. There is also an over­load of the ToString method which takes a for­mat string to allow you to return the inte­ger val­ue, string name, or hexdec­i­mal rep­re­sen­ta­tion, see the exam­ples here.

To con­vert from a string name of a enum ele­ment back to its enum form you’ll need the help of the Enum class:

string redString = MyColours.Red.ToString(); // this returns "Red"
MyColours red = (MyColours)Enum.Parse(typeof(MyColours), redString); // this returns MyColours.Red

There are some oth­er use­ful meth­ods on the Enum class such as IsDe­fined too, see the list of avail­able meth­ods here.