loop over Enum values

  • Thread starter Thread starter giant food
  • Start date Start date
G

giant food

This seems like a long shot, but I wondered if there's a way to loop
over the values in an Enum. For example, say I have an Enum as
follows:

Public Enum statusValues
Ready
Running
Finished
Error
End Enum

'.....

I'd like to be able to loop over and print out these values' names
something like this:

For Each item in statusValues
Console.WriteLine(item.ToString)
Next


....the reason being that, if I add elements to my Enum object, I won't
have to go change the code that prints out their names. Thanks!

--Frank
 
This seems like a long shot, but I wondered if there's a way to loop
over the values in an Enum. For example, say I have an Enum as
follows:

Public Enum statusValues
Ready
Running
Finished
Error
End Enum

'.....

I'd like to be able to loop over and print out these values' names
something like this:

For Each item in statusValues
Console.WriteLine(item.ToString)
Next

...the reason being that, if I add elements to my Enum object, I won't
have to go change the code that prints out their names. Thanks!

--Frank

The Enum class has static methods that allow you to do this.
For example, to get the name of a specific enum value that was passed to
you, you could use
string name = Enum.GetName(typeof(MyEnumType),SomeEnumValue)
 
Frank,
Remember, all enums inherit from System.Enum, System.Enum has shared methods
for retrieving information about Enums.

Try something like:
For Each item in [Enum].GetValues(GetType(statusValues))
Console.WriteLine(item.ToString)
Next

If you want the names of the Enum instead of the values, try:
For Each item in [Enum].GetNames(GetType(statusValues))
Console.WriteLine(item.ToString)
Next

The [Enum] is an escaped identifier it allows me to refer to the System.Enum
type instead of the Enum keyword used to define an Enum.

Other useful members of System.Enum include: Format, GetName, IsDefined,
Parse, and ToObject.

Hope this helps
Jay
 
* (e-mail address removed) (giant food) scripsit:
This seems like a long shot, but I wondered if there's a way to loop
over the values in an Enum. For example, say I have an Enum as
follows:

Public Enum statusValues
Ready
Running
Finished
Error
End Enum

'.....

I'd like to be able to loop over and print out these values' names
something like this:

For Each item in statusValues
Console.WriteLine(item.ToString)
Next

\\\
Dim s As String
For Each s In [Enum].GetNames(GetType(KnownColor))
Me.ListBox1.Items.Add(s)
Next s
///

Replace 'KnownColor' with the name of your enum.
 
Back
Top