Sunday, December 26, 2010

How to Convert an Enum to its String Value

If you ever need to get the string value of an Enum member you can do so using the following technique rather than using a reverse lookup table:

Electronic electronic = Electronic.Breakbeat;
// value = "Breakbeat";
string value = Enum.GetName(typeof(Enums.Electronic), electronic);  

Where Electronic is an Enum declared like this:

public enum Electronic
{
   AcidHouse,
   Ambient,
   BigBeat,
   Breakbeat,
   Dance,
   Demo,
   Disco,
   Downtempo,
   DrumandBass,
...
...

Also, if you want to get the count of items in an enum in Silverlight you will have to create your version of Enum.GetValues so this method is not included in the framework:

public static IEnumerable<T> GetValues<T>()
{
   Type type = typeof(T);
   if (!type.IsEnum)
   {
       //  throw Exception
   }
   FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Static);
   foreach (var item in fields)
   {
       yield return (T)item.GetValue(null);
   }
}
int length = GetValues<Electronic>().Count();

Read more: Silverlight tips of the day