Home > Articles > Programming

  • Print
  • + Share This
This chapter is from the book

Working with Enumerations

An enumeration is a special data type that the user defines. At its core, an enumeration is a list of constants, but it is the ability to group these constants that makes an enumeration so powerful. Say, for example, that you were creating a service that tracked travel tickets, and each ticket sold could belong to a train, plane, or car. You could create an enumeration called vehicle and have it contain constants for each of the vehicle types.

To create an enumeration, you declare a variable of type enum, as shown in line 1 of Listing 10.5 (10.6 for C#). You then type your constant names—in this case the colors red, blue, and green—before you end the enum. You can now create variables of type Color in your service.

Listing 10.5 Returning an Enumeration in VB

1:  Public Enum Color
2:   Red = 1
3:   Blue = 2
4:   Green = 3
5:  End Enum
7:  <WebMethod()> Public Function EnumReturn() As Color
8:   Return Color.Red
9:  End Function

Listing 10.6 Returning an Enumeration in C#

1:  public enum Color
2:   {
3:   Red = 1,
4:   Blue = 2,
5:   Green = 3 		
6:   }
8:  [WebMethod]
9:  public Color EnumReturn()
10:  {
11:   return Color.Red;
12:  }

To return your Color enumeration from an XML Web service, simply declare your method as returning type Color (see Listings 10.5 and 10.6) and return a color. The syntax for retrieving a value from an enumeration is as follows:


In the examples above, you return:


When an XML Web service returns an enumeration, it actually returns the value's name, not its value. In the example above, the service returns a data type Color with a value of Red (see Figure 10.2).

Figure 10.2 Returning an enumeration from an XML Web service.
  • + Share This
  • 🔖 Save To Your Account