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.