Aug 14 2011

C# – Listing enumerations with their properties

A small supplementary post about how to list every element of an enumeration alongside a property derived from a method that uses the element.

I encountered this problem when wanting to list the various biomes in my World Generation project alongside the color they were represented by on the terrain. The first step was to convert the enumeration to an array of strings (listing each of the enum’s elements), which can easily be achieved with the following code:

string[] biomes = Enum.GetNames(typeof(BiomeType));

Where BiomeType was the name of the enum. This was all very well to write as a list to the screen but now I wanted to be able to covert each of the elements back from its string form to its enumeration form, in order to pass it through the method that returns the terrain color. After some investigation I found the following method to achieve this:

(BiomeType)Enum.Parse(typeof(BiomeType), biome))

Again where BiomeType was the name of the enumeration and biome was the element in string form.

Hopefully this short post will help at least one person at some point!

Leave a Reply

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

× 7 = fifty six

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>