Wael Dalloul
Wael Dalloul

Reputation: 23014

How to retrieve an Enum member given its name

It's very easy I have the following Enum

Public Enum TCheckStatus
        Checked
        NotChecked
        Indeterminate 
    End Enum

I want to get the Index of the given name found in the enum, what's the best way?!!

For Example:

Suppose I have "NotChecked" string , I want the output to be 1

Upvotes: 1

Views: 5365

Answers (5)

Raymond Fung
Raymond Fung

Reputation: 11

int Output = (int)Enum.Parse(typeof(TCheckStatus), "NotChecked");

Upvotes: 1

John Woo
John Woo

Reputation: 263723

try this:

Dim val as integer = cint(DirectCast([Enum].Parse(GetType(TCheckStatus), _
                          "NotChecked"), TCheckStatus)

StackOverflow - Parse a string to an Enum value in VB.NET

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460108

You are looking for Enum.GetNames. It retrieves an array of the names of the constants in a specified enumeration.

Dim notCheckedStatus  = DirectCast([Enum].Parse(GetType(TCheckStatus), "NotChecked"), TCheckStatus)
Dim allStatusNames    = [Enum].GetNames(GetType(TCheckStatus))
Dim indexOfNotChecked = Array.IndexOf(AllStatusNames, "NotChecked") '=1'
  1. line: parses a string variable to an enum-value
  2. line: returns all enum-values of a given enum-type as Array
  3. line: returns the index of a given enum-value in that Array

Of course to solve your question you only need this:

Array.IndexOf([Enum].GetNames(GetType(TCheckStatus)), "NotChecked") 

Upvotes: 2

Anil
Anil

Reputation: 965

To get arrays of the names and their integer equivalents with the Enum methods in VB.net, please use GetNames() and GetValues() method. Use Parse() to get the index. Hope this helps.

Upvotes: 1

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

I can't give precise vb syntax, but I'll write it in C# so see if you can use it:

int index = (int)Enum.Parse( typeof(TCheckStatus), "NotChecked");

index is 1 in this case. If you give an invalid string (not a member of the enum), it will throw an exception. If this is not what you want, you can use Enum.TryParse instead.

If you already have the enum, you can just cast it to a int to get the index:

var myEnum = TCheckStatus.NotChecked;
int index = (int)myEnum;

Upvotes: 2

Related Questions