Created
June 30, 2013 09:54
-
-
Save RANUX/5894571 to your computer and use it in GitHub Desktop.
Extended Enum with attributes
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 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