Convert the Name of an Enumerated Value into the Value

Problem

You want to set an enumeration using the string name of a value, not the integer value, or you want to retrieve all the names used for constants in an enumeration.

Solution

Use the Enum.GetNames method to get an array of all enumeration names and the Enum.Parse method to convert a string into the corresponding value from an enumeration.

Discussion

An enumeration is a group of integer constants with descriptive names. Usually, you’ll use enumeration values by name. Sometimes, however, it’s necessary to convert enumeration values into strings, and vice versa. One reason might be to provide a user with a list of enumerated values and give them the chance to choose one.

As an example, consider ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.