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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.