Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Gets the description for a enum value
- /// </summary>
- /// <typeparam name="T">Enum type</typeparam>
- /// <param name="e">Enum value</param>
- /// <returns>A description if one esists.</returns>
- public static string GetDescription<T>(this T e) where T : IConvertible
- {
- if (!(e is System.Enum)) return null;
- var type = e.GetType();
- var values = System.Enum.GetValues(type);
- foreach (var val in values)
- {
- if ((int) val != e.ToInt32(CultureInfo.InvariantCulture)) continue;
- var memInfo = type.GetMember(type.GetEnumName(val) ?? throw new InvalidOperationException());
- if (memInfo[0]
- .GetCustomAttributes(typeof(DescriptionAttribute), false)
- .FirstOrDefault() is DescriptionAttribute descriptionAttribute)
- {
- return descriptionAttribute.Description;
- }
- }
- return null;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement