using System.ComponentModel;
using System.Reflection;
namespace Azaion.Common.Extensions;
/// Enum extensions
public static class EnumExtensions
{
/// Get all enums with descriptions
public static Dictionary GetDescriptions() where T : Enum =>
Enum.GetValues(typeof(T)).Cast()
.ToDictionary(x => x, x => x.GetEnumAttrib()?.Description ?? x.ToString());
///
/// Get the Description from the DescriptionAttribute.
///
///
///
public static string GetDescription(this Enum enumValue)
{
return enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute()?
.Description ?? enumValue.ToString();
}
/// Get attribute for enum's member, usually is used for getting Description attribute
private static TAttrib GetEnumAttrib(this T value) where T: Enum
{
var field = value.GetType().GetField(value.ToString());
if (field == null)
return default!;
return field.GetCustomAttributes(typeof(TAttrib), false)
.Cast()
.FirstOrDefault()!;
}
///
/// Get default value for enum
///
///
///
public static TEnum GetDefaultValue() where TEnum : struct
{
var t = typeof(TEnum);
var attributes = (DefaultValueAttribute[])t.GetCustomAttributes(typeof(DefaultValueAttribute), false);
if (attributes is { Length: > 0 })
return (TEnum)attributes[0].Value!;
return default;
}
}