Use the ENUM object to manipulate Enumerated Values

Enums are a tremendously easy way to make your code understandable. In the bad old days, when working on someone else's program I'd be forced to decode code like this:

Dim cust As New Customer
cust.Type = 0

With an Enum, everything is more obvious:

Dim cust As New Customer
cust.Type = CustomerTypes.Deadbeat

What takes Enums to the next level are the static methods built into the Enum class. For instance, if I want to turn an Enum into an array of strings, I can use the Enum class's GetNames method:

Dim cTypes As String() = [Enum].GetNames(GetType(CustomerTypes))

Because of the way Visual Basic handles names, Enum has to be enclosed in brackets to prevent syntax errors. C# doesn't require those brackets:

string[] cTypes = Enum.GetNames(typeof(CustomerTypes));

I can then bind the output from GetNames to any listing control to get a list of the names in the Enum displayed in my user interface:

MyListBox.ItemsSource = Enum.GetNames(typeof(CustomerTypes));

GetNames shows the basic structure of the Enum class's static methods: the first parameter to any method is always the Type of the Enum you want to work with. For instance, if you have code in a Web Service that's passed the value of an Enum, you can convert that value into the name of the corresponding Enum entry using the Enum class's GetName method. As before, the first parameter is the type of the Enum; the second parameter is the value you're looking up:

Dim inputValue As Integer = 1
Me.MyTextBox.Text = [Enum].GetName(GetType(CustomerTypes), inputValue)

Parse goes one better and converts a string containing one of the names in an Enum into the Enum item itself. This code, for instance, sets the Customer object's Type property to the appropriate Enum item based on a string value:

Dim custTypeString As String = "DeadBeat"
cust.Type = [Enum].Parse(
                GetType(CustomerTypes), custTypeString);

Visual Basic doesn't require the explicit cast to use Parse:

string custTypeString = "DeadBeat";
cust.Type = (CustomerTypes) Enum.Parse(
                typeof(CustomerTypes), custTypeString);

If the string value you're passing to Parse isn't an item in the Enum, the Parse method throws an exception. To avoid that, you can use the Enum's TryParse method which, while it still won't do the conversion, won't throw an exception either. An even better answer is to use the Enum's IsDefined method to see if the item exists before trying to retrieve it:

if (Enum.IsDefined(typeof(CustomersType), custTypeString))
{
  Customers ctype = (CustomersType) Enum.Parse(
typeof(CustomersType), custTypeString);
}
else
{
   ErrorLabel.Text = "Not a valid customer type.";
}
(Taken from a blog.)
Ebook Download
View all
Learn
View all