Skip to content

Instantly share code, notes, and snippets.

@AvgustPol
Last active August 25, 2020 11:21
Show Gist options
  • Save AvgustPol/9de443977017d9eaa181d2c044656f55 to your computer and use it in GitHub Desktop.
Save AvgustPol/9de443977017d9eaa181d2c044656f55 to your computer and use it in GitHub Desktop.
EnumExtension -> GetDescription()
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;
}
}
}
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