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