1
0
Files
common/AMWD.Common/Extensions/EnumExtensions.cs
2021-10-22 21:12:32 +02:00

45 lines
1.6 KiB
C#

using System.Collections.Generic;
using System.ComponentModel;
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();
}
}