Fun with Enums

One of the seemingly lesser known features of Enums is their ability to convert to and from the name rather than the value, so I thought I’d do a quick refresher.

Consider the following Enum…
Medal.Bronze = 0
Medal.Silver = 1
Medal.Gold = 2

The majority of cases people leave it as an int (can be any non-char integral type). However, what happens when you want to store/persist the type? If I was to save this to a disk file I might choose to use XML and have a result like…
<Medal>2</Medal>
Then when I load the XML back I can easily convert it back…
Medal medal = (int)Convert.ToInt32("2");
However, I don’t actually like this, the value of 2 has no real meaning to the reader, I’d much prefer to see
<Medal>Gold</Medal>
Well it is possible. To save the name rather than the value you can use ToString and a format string…
medal.ToString("G");
Reading the name back into the enum uses the often overlooked Parse method…
Medal medal = (Medal)Enum.Parse(typeof(Medal), "Gold");
Admittedly this doesn’t solve localization problems of having XML, "human readable" but I prefer it.

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s