Advertisement
Jarquafelmu

Untitled

Aug 5th, 2019
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.82 KB | None | 0 0
  1. /// <summary>
  2. /// Gets the description for a enum value
  3. /// </summary>
  4. /// <typeparam name="T">Enum type</typeparam>
  5. /// <param name="e">Enum value</param>
  6. /// <returns>A description if one esists.</returns>
  7. public static string GetDescription<T>(this T e) where T : IConvertible
  8. {
  9.     if (!(e is System.Enum)) return null;
  10.  
  11.     var type = e.GetType();
  12.     var values = System.Enum.GetValues(type);
  13.                
  14.     foreach (var val in values)
  15.     {
  16.         if ((int) val != e.ToInt32(CultureInfo.InvariantCulture)) continue;
  17.  
  18.         var memInfo = type.GetMember(type.GetEnumName(val) ?? throw new InvalidOperationException());
  19.  
  20.         if (memInfo[0]
  21.             .GetCustomAttributes(typeof(DescriptionAttribute), false)
  22.             .FirstOrDefault() is DescriptionAttribute descriptionAttribute)
  23.         {
  24.             return descriptionAttribute.Description;
  25.         }
  26.     }
  27.  
  28.     return null;
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement