.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

  • ML.NET Improves Object Detection

    Microsoft improved the object detection capabilities of its ML.NET machine learning framework for .NET developers, adding the ability to train custom models with Model Builder in Visual Studio.

  • More Improvements for VS Code's New Python Language Server

    Microsoft announced more improvements for the new Python language server for Visual Studio Code, Pylance, specializing in rich type information.

  • Death of the Dev Machine?

    Here's a takeaway from this week's Ignite 2020 event: An advanced Azure cloud portends the death of the traditional, high-powered dev machine packed with computing, memory and storage components.

  • COVID-19 Is Ignite 2020's Elephant in the Room: 'Frankly, It Sucks'

    As in all things of our new reality, there was no escaping the drastic changes in routine caused by the COVID-19 pandemic during Microsoft's big Ignite 2020 developer/IT pro conference, this week shifted to an online-only event after drawing tens of thousands of in-person attendees in years past.

  • Visual Studio 2019 v16.8 Preview Update Adds Codespaces

    To coincide with the Microsoft Ignite 2020 IT pro/developer event, the Visual Studio dev team shipped a new update, Visual Studio 2019 v16.8 Preview 3.1, with the main attraction being support for cloud-hosted Codespaces, now in a limited beta.

Upcoming Events