Skip to content

Instantly share code, notes, and snippets.

@gabehesse
Created June 1, 2011 16:53
Show Gist options
  • Save gabehesse/1002735 to your computer and use it in GitHub Desktop.
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.
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"
@vyarthrot
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment