using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Threading;
/// The EnumExtensions class
///
public static class EnumExtensions
{
/// The EnumStorage class
///
private class EnumStorage
{
public static readonly Dictionary> Description = new Dictionary>();
}
///
/// Returns the localized value of the DisplayAttribute or DescriptionAttribute or the enum.ToString()
///
/// The enum for which to return
///
/// You need to decorate your enum with attributes like these:
/// [Display(Description = "MyResourceName", ResourceType = typeof(MyResourceTypeName))]
/// or
/// [Description("My custom description text - not localizable")]
///
/// Please NOTE that the value is cached per culture info and enum value for faster subsequent access.
///
///
[DebuggerStepThrough]
public static string AsString(this T @enum) //ext method
where T : struct, IComparable, IFormattable, IConvertible
{
string result;
Dictionary dic;
var cultureHash = Thread.CurrentThread.CurrentUICulture.GetHashCode();
if (!EnumStorage.Description.TryGetValue(cultureHash, out dic))
{
dic = new Dictionary();
EnumStorage.Description[cultureHash] = dic;
}
if (dic.TryGetValue(@enum, out result))
return result;
if (@enum is int)
return @enum.ToString();
var type = @enum.GetType();
MemberInfo[] memInfo = type.GetMember(@enum.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
if (attrs != null && attrs.Length > 0)
result = ((DisplayAttribute)attrs[0]).GetDescription();
else
{
attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
result = ((DescriptionAttribute)attrs[0]).Description;
}
}
if (result == null)
result = @enum.ToString();
dic[@enum] = result;
return result;
}
}