Skip to content

Instantly share code, notes, and snippets.

@gabehesse
Created June 1, 2011 16:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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"
@jslicer
Copy link

jslicer commented Jan 13, 2014

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 the enum member's name instead (via regex):

    private static readonly Regex nonAlpha = new Regex("((?<=[a-z])[A-Z]|[A-Z](?=[a-z]))", RegexOptions.Compiled);

    /// <summary>
    /// Gets the description.
    /// </summary>
    /// <param name="enumType">Type of the enum.</param>
    /// <returns>The description on the enum member, or the name, with non-alpha characters replaced by
    /// spaces.</returns>
    internal static string GetDescription(this Enum enumType)
    {
        var sb = new StringBuilder();
        var notFirst = false;

        foreach (var attr in enumType.GetType().GetField(enumType.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false))
        {
            if (notFirst)
            {
                sb.AppendLine();
            }

            sb.Append(((DescriptionAttribute)attr).Description);
            notFirst = true;
        }

        var description = sb.ToString();

        return string.IsNullOrEmpty(description)
            ? nonAlpha.Replace(enumType.ToString(), " $1").Trim()
            : description;
    }

@vyarthrot
Copy link

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