This extension class adds an extension method to the Enum type. This created the ability for each value of an Enumeration to have a default text value associated with it by simple adding an attribute to each enum value.
public enum MyEnum
{
[DisplayValue("#FFFFFF")]
White
}
static public class EnumExtension
{
///
/// Will get the string value for a given enums value, this will
/// only work if you assign the StringValue attribute to
/// the items in your enum.
///
///
///
public static string GetDisplayValue(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
DisplayValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(DisplayValueAttribute), false) as DisplayValueAttribute[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].DisplayValue : null;
}
}
Published by