Last active
August 25, 2020 11:21
-
-
Save AvgustPol/9de443977017d9eaa181d2c044656f55 to your computer and use it in GitHub Desktop.
EnumExtension -> GetDescription()
This file contains hidden or 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
| using System; | |
| using System.ComponentModel; | |
| using System.Globalization; | |
| using System.Linq; | |
| namespace Project.Models.Common | |
| { | |
| public static class EnumExtensions | |
| { | |
| public static string GetDescription<T>(this T e) where T : IConvertible | |
| { | |
| if (e is Enum) | |
| { | |
| Type type = e.GetType(); | |
| Array values = System.Enum.GetValues(type); | |
| foreach (int val in values) | |
| { | |
| if (val == e.ToInt32(CultureInfo.InvariantCulture)) | |
| { | |
| var memInfo = type.GetMember(type.GetEnumName(val)); | |
| var descriptionAttribute = memInfo[0] | |
| .GetCustomAttributes(typeof(DescriptionAttribute), false) | |
| .FirstOrDefault() as DescriptionAttribute; | |
| if (descriptionAttribute != null) | |
| { | |
| return descriptionAttribute.Description; | |
| } | |
| } | |
| } | |
| } | |
| return string.Empty; | |
| } | |
| } | |
| } |
This file contains hidden or 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
| using System.ComponentModel; | |
| public enum ExampleEnum | |
| { | |
| [Description("This description will be rendered")] | |
| Foo = 100, | |
| [Description("Blah blah blah")] | |
| Boo = 300, | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment