Skip to content

Instantly share code, notes, and snippets.

@robfe
Created April 9, 2013 02:54
Show Gist options
  • Save robfe/5342558 to your computer and use it in GitHub Desktop.
Save robfe/5342558 to your computer and use it in GitHub Desktop.
reads System.ComponentModel.DescriptionAttributes for each value in an enum, and provides two-way mapping.
static class EnumDescriptionMapper<T>
{
public static readonly Dictionary<T, string> EnumDescriptions;
public static readonly Dictionary<string, T> DescriptionsValues;
static EnumDescriptionMapper()
{
var values = (T[])Enum.GetValues(typeof(T));
EnumDescriptions = values.ToDictionary(x => x, GetAttributeDescription);
DescriptionsValues = EnumDescriptions.ToDictionary(x => x.Value, x => x.Key);
}
static string GetAttributeDescription(T t)
{
string name = t.ToString();
var d = typeof(T).GetField(name).GetCustomAttribute<DescriptionAttribute>();
return d == null ? name : d.Description;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment