C# using numbers in an enum

No identifier at all in C# may begin with a number (for lexical/parsing reasons). Consider adding a [Description] attribute to your enum values:

public enum myEnum
    OneA = 1,
    TwoA = 2,
    ThreeA = 3,

Then you can get the description from an enum value like this:

    typeof(myEnum).GetFields(BindingFlags.Public | BindingFlags.Static)
        .Single(x => (myEnum)x.GetValue(null) == enumValue),    

Based on XSA’s comment below, I wanted to expand on how one could make this more readable. Most simply, you could just create a static (extension) method:

public static string GetDescription(this Enum value)
    return ((DescriptionAttribute)Attribute.GetCustomAttribute(
        value.GetType().GetFields(BindingFlags.Public | BindingFlags.Static)
            .Single(x => x.GetValue(null).Equals(value)),
        typeof(DescriptionAttribute)))?.Description ?? value.ToString();

It’s up to you whether you want to make it an extension method, and in the implementation above, I’ve made it fallback to the enum’s normal name if no [DescriptionAttribute] has been provided.

Now you can get the description for an enum value via:


Leave a Comment