Skip to content

Instantly share code, notes, and snippets.

@RANUX
Created June 30, 2013 09:54
Show Gist options
  • Save RANUX/5894571 to your computer and use it in GitHub Desktop.
Save RANUX/5894571 to your computer and use it in GitHub Desktop.
Extended Enum with attributes
public class EnumExtension
{
enum Test {
[Description("This is a foo")]
Foo,
[Description("This is a bar")]
Bar
}
public static class DescriptionExtensions
{
public static string GetDescriptionValue(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
DescriptionAttribute[] attribs = fieldInfo.GetCustomAttributes( typeof(DescriptionAttribute), false ) as DescriptionAttribute[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].Description : null;
}
public void UsageSample()
{
Test test = Test.Foo;
// will show "This is a foo"
Console.WriteLine(test.GetDescription());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment