Add more examples of information for enumerations with the feature of attribute

  • 2020-06-12 10:17:22
  • OfStack

While the feature (Attribute) is a way to associate additional data with a property (and other constructs), enumerations are the most common constructs in programming. Enumerations are essentially 1 constant value, and they provide better readability than using them directly. We know that the enumeration types can only be the basis of the value type (byte, sbyte, short, ushort, int, uint, long or ulong), 1 case of enumeration can meet our requirements, but sometimes we need to raise additional more information, it is not enough to only use these value types, then through application of enum type features can make the enumeration with more information.

Use the DescriptionAttribute feature in enumerations

First, the using ES16en. ComponentModel namespace is introduced. Here is an enumeration that applies the DescriptionAttribute feature:


enum Fruit
{
    [Description(" apple ")]
    Apple,
    [Description(" The oranges ")]
    Orange,
    [Description(" watermelon ")]
    Watermelon
}

Here is an extension of the Description feature:


/// <summary>
///  Gets the enumeration description property value 
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <param name="enumerationValue"> Enumerated values </param>
/// <returns> A description of an enumeration value /returns>
public static string GetDescription<TEnum>(this TEnum enumerationValue)
   where TEnum : struct, IComparable, IFormattable, IConvertible
{
   Type type = enumerationValue.GetType();
   if (!type.IsEnum)
   {
  throw new ArgumentException("EnumerationValue It must be 1 An enumeration values ", "enumerationValue");
   }

   // Use reflection to get the member information for the enumeration 
   MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
   if (memberInfo != null && memberInfo.Length > 0)
   {
  object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

  if (attrs != null && attrs.Length > 0)
  {
 // Returns enumeration worth description information 
 return ((DescriptionAttribute)attrs[0]).Description;
  }
   }
   // Returns the enumeration value as a string if there is no value describing the property 
   return enumerationValue.ToString();
}

Finally, we can use the extension method to get the enumeration worth description information:


public static void Main(string[] args)
{
//description = " The oranges "
string description = Fruit.Orange.GetDescription();
}


Related articles: