1
0
Files
common/AMWD.Common/Extensions/EnumExtensions.cs

54 lines
2.0 KiB
C#

using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace System
{
/// <summary>
/// Extend the enum values by attribute driven methods.
/// </summary>
public static class EnumExtensions
{
/// <summary>
/// Returns a list of specific attribute type from a enum-value.
/// </summary>
/// <typeparam name="TAttribute">The attribute type.</typeparam>
/// <param name="value">The enum value.</param>
/// <returns>The attributes or null.</returns>
public static IEnumerable<TAttribute> GetAttributes<TAttribute>(this Enum value)
{
var fieldInfo = value.GetType().GetField(value.ToString());
if (fieldInfo == null)
return Array.Empty<TAttribute>();
return fieldInfo.GetCustomAttributes(typeof(TAttribute), inherit: false).Cast<TAttribute>();
}
/// <summary>
/// Returns a specific attribute from a enum-value.
/// </summary>
/// <typeparam name="TAttribute">The attribute type.</typeparam>
/// <param name="value">The enum value.</param>
/// <returns>The attribute or null.</returns>
public static TAttribute GetAttribute<TAttribute>(this Enum value)
=> value.GetAttributes<TAttribute>().FirstOrDefault();
/// <summary>
/// Returns the description from <see cref="DescriptionAttribute"/>.
/// </summary>
/// <param name="value">The enum value.</param>
/// <returns>The description or the string representation of the value.</returns>
public static string GetDescription(this Enum value)
=> value.GetAttribute<DescriptionAttribute>()?.Description ?? value.ToString();
/// <summary>
/// Returns the name from <see cref="DisplayAttribute"/>.
/// </summary>
/// <param name="value">The enum value.</param>
/// <returns>The display name or the string representation of the value.</returns>
public static string GetDisplayName(this Enum value)
=> value.GetAttribute<DisplayAttribute>()?.Name ?? value.ToString();
}
}