Enumerating the Possibilities
Taking Advantage of the Enum Class
October 30, 2009
Class Act
LANGUAGES: VB
TECHNOLOGIES: Enumerations| Enum class
Enumeratingthe Possibilities
TakingAdvantage of the Enum Class
By Ken Getz
Whendescribing the behavior of an object, it s often useful to provide a list ofpossible options for a specific property. For example, the Calendar control provides a FirstDayOfWeekproperty, and its value can be Default, Sunday, Monday,etc. The TitleFormat property can beeither Month or MonthYear. The Calendar control and many other objects provide groups of integerconstants that indicate how you want properties to behave. These groups arecalled enumerations, and you can create your own in addition to theenumerations the .NET Framework provides.
To makeit possible for you to interact with enumerations programmatically, the .NETFramework provides the Enum class.Besides the methods this class inherits from the base Object class, you ll find the shared methods (or static methods,for C# developers) shown in FIGURE 1. In this article, I ll demonstrate how touse most of these methods in two sample pages. In addition, I ll describe howto create your own enumerations and how to interact with them programmatically.
Method | Description |
---|---|
Format | Format converts an enumerated value to an equivalent string representation by using the supplied format specifier. |
GetName | Given an enumerated value, GetName retrieves the named constant corresponding to the value. |
GetNames | GetNames retrieves an array of strings corresponding to the items in the enumeration, in order by numeric value. |
GetUnderlyingType | GetUnderlyingType retrieves the underlying type of the enumeration (any integral type except Char). |
GetValues | GetValues retrieves an Array object containing all the numeric items in the enumeration. |
IsDefined | IsDefined returns True if an item with the specified value exists within the enumeration. |
Parse | Parse converts from a string representation of one or more items into the corresponding numeric value. This is, effectively, the inverse of the GetName method. |
ToObject | ToObject retrieves an instance of the enumeration, of the specified value. You can get by without this for the most part, except in rare cases in which you require an Object type. (See the SetValue method of the PropertyInfo class in the Reflection namespace for an example of where this might be useful.) |
FIGURE1: Use theseshared methods of the Enum class tointeract with items programmatically.
Working with Names and Values
To makeit possible for you to iterate through an enumeration s names and values, the Enumclass provides two useful methods: GetNames and GetValues. The GetNamesmethod returns an array containing the names in the enumeration, in order bythe values each name represents. The GetValues method returns an arraycontaining all the values in order. (Interestingly, the GetNames methodreturns an array of strings defined as String. The GetValuesmethod returns an array defined as Array. You can t treat these the sameway, as you ll see in the code.)
Imagineyou d like to supply users a drop-down list containing all the items within anenumeration and allow them to choose from the list. For example, the Calendarcontrol provides enumerations defining values for several of its properties,including the FirstDayOfWeek, TitleFormat, and DayFormatproperties. Each of these properties accepts a value from an enumeration withthe same name as the property itself. FIGURE 2 shows a sample page, Calendar.aspx, that demonstrates twodifferent techniques for filling a list control. (The sample uses the DropDownListcontrol, but you could use the same techniques for any control that inheritsfrom the ListControl base class, including the ListBox, CheckBoxList,and RadioButtonList controls.)
FIGURE 2: Use this sample page to test theprocess of filling list controls with values from an enumeration and retrievingthe value once you select an item from the list.
FIGURE 3 shows what the sample page s Page_Load event handler looks like.
Private Sub Page_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
If Not Page.IsPostBackThen
FillListWithEnum1(ddlFirstDayOfWeek, _
GetType(FirstDayOfWeek))
FillListWithEnum1(ddlDayNameFormat, _
GetType(DayNameFormat))
FillListWithEnum2(ddlTitleFormat, _
GetType(TitleFormat))
FillExistingItems()
End If
End Sub
FIGURE3: Calendar.aspx sPage_Load event handler.
The first method, FillListWithEnum1,uses the code shown in FIGURE 4 to do its work.
Private Sub FillListWithEnum1( _
ByVal lc As ListControl, ByVal typ As Type)
If typ.IsEnum Then
lc.Items.Clear()
Dim obj As Object
Dim li As ListItem
For Each obj In System.Enum.GetValues(typ)
li = New ListItem()
li.Text = System.Enum.GetName(typ, obj)
li.Value = CStr(obj)
lc.Items.Add(li)
Next
End If
End Sub
FIGURE 4:The FillListWithEnum1 method.
First,this procedure checks to ensure it was passed an enumeration (by calling the IsEnum method of the System.Type object passed to it). Ifso, the procedure clears the items from the DropDownList control and iterates through each item in the Array object that is returned when youcall the GetValues method:
For Each obj InSystem.Enum.GetValues(typ)
' ...
Next obj
For eachitem in the enumeration, the code creates a new ListItem object and calls the GetNamemethod to retrieve the name corresponding to the selected enumeration item. Thecode fills in the ListItem object s Text and Value properties and adds the ListItemto the control: