Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list Enum's members

Tags:

How to list Enum's members in code? I have the following Enum:

Public Enum TestEnum As int32     First = 0     Second = 2     Third = 4     Fourth = 6 End Enum 

And I try to list all members of TestEnum via the following code but it failed:

Public Class Form1      Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click         Dim Enum1 As TestEnum          Dim Members() As String          Members = System.Enum.GetNames(CType(Enum1, System.Enum))       End Sub End Class 

So, my question is: How to list members of an Enum?

Update: The solution is:

Public Class Form1      Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click         Dim Members() As String         Members = System.Enum.GetNames(GetType(TestEnum))          MessageBox.Show(Join(Members, Chr(13) & Chr(10)))      End Sub End Class 
like image 719
user774411 Avatar asked Jun 07 '11 17:06

user774411


2 Answers

You can simply iterate through all values like this:

Public Enum TestEnum As int32     First = 0     Second = 2     Third = 4     Fourth = 6 End Enum  For Each tstEnum As TestEnum In System.Enum.GetValues(GetType(TestEnum))      Response.Write(         String.Format("Name: {0}  Value: {1}",              tstEnum.ToString,              CInt(tstEnum).ToString         )     )  Next 
like image 53
George Filippakos Avatar answered Oct 07 '22 01:10

George Filippakos


You need to pass a type, not a value, to the method.

Members = System.Enum.GetNames(GetType(TestEnum)) 

If you have an instance of your enum you can also use

Members = System.Enum.GetNames(Enum1.GetType()) 

Though I would recommend the first approach if you know the type you want.

like image 41
Sven Avatar answered Oct 06 '22 23:10

Sven