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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More C# enum examples...
http://csharp.net-informations.com/statements/enum.htm