Nianios
Nianios

Reputation: 1436

Enum memberlist starts with number

I face a problem with an enum that I have built.

  Public Enum enumGraphType
    Table = 0
    Chart = 1
    Gauge = 2
    3DChart = 3
  End Enum

I get an error for 3DChart : Statement cannot appear within an Enum body. End of Enum assumed.
I know that I can use the name D3Chart but this is not what I want.
Also I know that I can add an attribute (like Description) and have my description as 3DChart, but this is not what I want.
Also I have tried [3DChart] and it doesn't work.
Is any way to work around that and keep the name?

Thank you for your time

Upvotes: 2

Views: 385

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460340

Enum members cannot start with numbers, so this is not valid:

3DChart = 3

You could prepend an underscore instead

_3DChart = 3

For what it's worth, you could add a description:

Public Enum EnumGraphType
    <ComponentModel.Description("Table")>
        Table = 0
    <ComponentModel.Description("Chart")>
        Chart = 1
    <ComponentModel.Description("Gauge")>
        Gauge = 2
    <ComponentModel.Description("3DChart")>
        _3DChart = 3
End Enum

Here's an enum-extension which returns it:

Public Module EnumExtensions
    <Runtime.CompilerServices.Extension()>
    Public Function GetDescription(ByVal EnumConstant As [Enum]) As String
        Dim fi As Reflection.FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())
        Dim attr() As ComponentModel.DescriptionAttribute =
            DirectCast( _
                fi.GetCustomAttributes(GetType(ComponentModel.DescriptionAttribute), False),  _
                ComponentModel.DescriptionAttribute() _
            )
        If attr.Length > 0 Then
            Return attr(0).Description
        Else
            Return EnumConstant.ToString()
        End If
    End Function
End Module

Now you get the description in this way:

Dim chartType = EnumGraphType._3DChart
Dim chartTypeDesc = chartType.GetDescription() ' 3DChart

Upvotes: 2

Related Questions