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
{
    [Description("1A")]
    OneA = 1,
    [Description("2A")]
    TwoA = 2,
    [Description("3A")]
    ThreeA = 3,
};

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

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

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:

myEnum.OneA.GetDescription()

No, there isn't. C# does not allow identifiers to start with a digit.

Application usability note: In your application you should not display code identifiers to the end-user anyway. Think of translating individual enumeration items into user-friendly displayable texts. Sooner or later you'll have to extend the enum with an item whose identifier won't be in a form displayable to the user.

UPDATE: Note that the way for attaching displayable texts to enumeration items is being discusses, for example, here.


An identifier in C# (and most languages) cannot start with a digit.

If you can modify the code that populates a dropdown with the enumeration names, you could maybe have a hack that strips off a leading underscore when populating the dropdown and define your enum like so:

public enum myEnum
{
  _1a = 1,
  _2a = 2,
  _3a = 3
};

Or if you don't like the underscores you could come up with your own 'prefix-to-be-stripped' scheme (maybe pass the prefix to the constructor or method that will populate the dropdown from the enum).

Tags:

C#

Syntax

Enums