How to get enum index value from an instance of the enum

Mike Lusicic 26 Reputation points
2024-07-31T15:24:31.27+00:00

I have some VB code where I have an enum and I have to convert the enum value to a corresponding string that is NOT the enum name. I do this by creating an array of these strings. The index into the array matches the underlying integer value of the enum value. The data portion looks like this:

Public Enum MessageOptions

SingleLine

TableOfLines

TableOfIDS

SingleID

End Enum

Private MessageOptionsText(3)

The array set up looks like this:

    `MessageOptionsText(0) = "S"`
````        MessageOptionsText(1) = "T"`

`        MessageOptionsText(2) = "N"`

`        MessageOptionsText(3) = "1"`

The value I want is assigned like this where MessageOption is of type MessageOptions:

```scala
    `wkRequestHeader += MessageOptionsText(Int(MessageOption))`
```How do I do this in c#?

Developer technologies C#
{count} vote

1 answer

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2024-07-31T19:44:44.2633333+00:00

    It is possible to use arrays in C# too, however, since the enumeration values are not always sequential starting from 0, it is more reliable to use a dictionary, for example.

    enum MessageOptions
    {
        SingleLine,
        TableOfLines,
        TableOfIDS,
        SingleID,
    }
    
    . . .
    
    Dictionary<MessageOptions, string> MessageOptionsText = new( ) 
    {
        [MessageOptions.SingleLine] = "S",
        [MessageOptions.TableOfLines] = "T",
        [MessageOptions.TableOfIDS] = "N",
        [MessageOptions.SingleID] = "1", 
    };
    
    
    // example:
    
    MessageOptions messageOption = MessageOptions.TableOfIDS;
    
    wkRequestHeader += MessageOptionsText[messageOption];
    

    It is also possible to use attributes.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.