Created
June 1, 2011 16:53
-
-
Save gabehesse/1002735 to your computer and use it in GitHub Desktop.
C# attribute that allows string representation of enum members & an extension method to get that string representation from an enum member.
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 EnumLabelAttribute : Attribute | |
{ | |
public string Label { get; private set; } | |
public EnumLabelAttribute(string label) { Label = label; } | |
} | |
public static class EnumLabelExtension | |
{ | |
public static string GetLabel(this Enum @enum) | |
{ | |
string value = null; | |
var fieldInfo = @enum.GetType().GetField(@enum.ToString()); | |
var attrs = fieldInfo.GetCustomAttributes(typeof(EnumLabelAttribute), false) as EnumLabelAttribute[]; | |
if (attrs != null) value = attrs.Length > 0 ? attrs[0].Label : null; | |
return value; | |
} | |
} | |
// ============================================================================================ | |
// sample usage | |
public enum Sample | |
{ | |
[EnumLabel("Hello World!")] | |
HelloWorld = 1, | |
[EnumLabel("Foo to the bar")] | |
FooBar = 2 | |
} | |
var label = Sample.FooBar.GetLabel(); // label is assigned the value "Foo to the bar" |
More C# enum examples...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In response to a comment left at http://codereview.stackexchange.com/a/39168/6172, I thought it might be interesting to post a version I wrote, which can handle multiple
[Description]
attributes, or one, or none. If there are none, it attempts to create a nicely-formatted version of theenum
member's name instead (via regex):