A week ago in a misguided attempt to make things easier, I created something like the following code. My mistake was not in creating the code necessarily, but in applying it to data driven auto generated enums. If you have those, don’t use this.
If you have nice, well behaved static enums wandering around your code and you wish you had a nice way to convert that enum to a usable Dictionary<int, string>, then you’ve come to the right place. So dress up that drab enum with a Description attribute like you see below and call EnumConverter.ConvertToDictionary<DrabEnum>();
And let me know how it works out.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Data.Linq;
using System.Text;
using System.Reflection;
using System.Collections;
namespace FunStuff
{
public enum FunEnum
{
[Description("Happy Enum")]
Happy = 1,
[Description("Sad Enum")]
Sad = 2
}
public static class EnumConverter
{
private static object lo = new object(); //used for locking access to the Cache
private static Dictionary<Type, Dictionary<int, string>> enumStore =
new Dictionary<Type, Dictionary<int, string>>();
/// <summary>
/// Returns thread safe copy of enum value and name dictionary. Where Description <br />
/// attribute exists, returns the description value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Dictionary<int, string> ConvertToDictionary<T>() where T : IComparable
{
lock (lo)
{
Type t = typeof(T);
if (!t.IsEnum) throw new ArgumentException("T must be an enum.");
if (!enumStore.ContainsKey(t)) enumStore.Add(t, Load(t));
return new Dictionary<int, string>(enumStore[t]);
}
}
private static Dictionary<int, string> Load(Type t)
{
Dictionary<int, string> list = new Dictionary<int, string>();
foreach (MemberInfo m in t.GetMembers())
{
if (m.MemberType == MemberTypes.Field && m.Name != "value__")
{
string label = m.Name;
foreach (var att in m.GetCustomAttributes(false))
{
DescriptionAttribute da = att as DescriptionAttribute;
if (null != da)
{
if (da.Description.Length > 0)
{
label = da.Description;
}
}
}
int id = Convert.ToInt32(System.Enum.Parse(t, m.Name));
list.Add(id, label);
}
}
return list;
}
}
}