Created
August 26, 2021 12:39
-
-
Save AntMooreWebDev/f82e69ae9bec6bcff33e0f2d0fb0b2ed to your computer and use it in GitHub Desktop.
Gets an attribute on an enum field value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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