Skip to content

Instantly share code, notes, and snippets.

@AntMooreWebDev
Created August 26, 2021 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AntMooreWebDev/f82e69ae9bec6bcff33e0f2d0fb0b2ed to your computer and use it in GitHub Desktop.
Save AntMooreWebDev/f82e69ae9bec6bcff33e0f2d0fb0b2ed to your computer and use it in GitHub Desktop.
Gets an attribute on an enum field value
public static class EnumHelper
{
/// <summary>
/// Gets an attribute on an enum field value"/>
/// </summary>
/// <typeparam name="T">The type of the attribute you want to retrieve</typeparam>
/// <param name="enumVal">The enum value</param>
/// <returns>The attribute of type T that exists on the enum value</returns>
/// <example><![CDATA[string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute>().Description;]]></example>
/// <see href="https://stackoverflow.com/a/9276348/3990156"/>
/// <seealso href="https://web.archive.org/web/20210826123339/https://stackoverflow.com/questions/1799370/getting-attributes-of-enums-value/9276348"/>
public static T GetAttributeOfType<T>(this Enum enumVal) where T : System.Attribute
{
var type = enumVal.GetType();
var memInfo = type.GetMember(enumVal.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
return (attributes.Length > 0) ? (T)attributes[0] : null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment