.NET Tips and Tricks

Blog archive

Use the Enum Object to Manipulate Enumerated Values

When it comes to writing Really Obvious Code, 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.";
}

Posted by Peter Vogel on 06/28/2013 at 1:16 PM


comments powered by Disqus

Featured

  • What's New in Visual Studio 2019 v16.5 Preview 2

    The second preview of Visual Studio 2019 v16.5 has arrived with improvements across the flagship IDE, including the core experience and different development areas such as C++, Python, web, mobile and so on.

  • C# Shows Strong in Tech Skills Reports

    Microsoft's C# programming language continues to show strong in tech industry skills reports, with the most recent examples coming from a skills testing company and a training company.

  • Color Shards

    Sharing Data and Splitting Components in Blazor

    ASP.NET Core Version 3.1 has at least two major changes that you'll want to take advantage of. Well, Peter thinks you will. Depending on your background, your response to one of them may be a resounding “meh.”

  • Architecture Small Graphic

    Microsoft Ships Preview SDK, Guidance for New Dual-Screen Mobile Era

    Microsoft announced a new SDK and developer guidance for dealing with the new dual-screen mobile era, ushered in by the advent of ultra-portable devices such as the Surface Duo.

  • How to Create a Machine Learning Decision Tree Classifier Using C#

    After earlier explaining how to compute disorder and split data in his exploration of machine learning decision tree classifiers, resident data scientist Dr. James McCaffrey of Microsoft Research now shows how to use the splitting and disorder code to create a working decision tree classifier.

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.

Upcoming Events