Working with Enumerations


Working with Enumerations

Suppose you want to represent the seasons of the year in a program. You could use the integers 0, 1, 2, and 3 to represent Spring, Summer, Fall, and Winter, respectively. This system would work, but it's not very intuitive. If you used the integer value 0 in code, it wouldn't be obvious that a particular 0 represented Spring. It also wouldn't be a very robust solution. For example, nothing would stop you from using any integer value rather than just 0, 1, 2, and 3. C# offers a better solution. You can use the enum keyword to create an enumeration type (sometimes called an enum type) whose values are limited to a set of symbolic names.

Declaring an Enumeration Type

Here's how to declare an enumeration type, called Season, whose literal values are limited to the symbolic names Spring, Summer, Fall, and Winter:

enum Season { Spring, Summer, Fall, Winter }

The symbolic names must appear between a pair of braces in a comma-separated list. Internally, an enumeration associates an integer value with each element. By default, the numbering starts at 0 for the first element and goes up in steps of 1.

Using an Enumeration

Once you have declared your enumeration type, you can use it in exactly the same way as any other type. If the name of your enumeration type is Season, you can create variables of type Season, fields of type Season, and parameters of type Season, as shown in this example:

enum Season { Spring, Summer, Fall, Winter }    class Example  {      public void Method(Season parameter)       {          Season localVariable;          ...      }        private Season currentSeason;  }

An enumeration type is a value type. Enumeration variables live on the stack (as discussed in Chapter 8). This is not really surprising when you remember that the underlying type of an enumeration is always an integral type.

Before you can use the value of an enumeration variable, it must be assigned a value. You can only assign valid values to an enumeration variable. For example:

Season colorful = Season.Fall;  Console.WriteLine(colorful);  // writes out 'Fall' 

Notice that you have to write Season.Fall rather than Fall. All enumeration literal names are scoped by their enumeration type. This is very useful because it allows different enumeration types to coincidentally contain literals with the same name. Also, notice that when you display an enumeration variable by using Console.WriteLine, the compiler generates code that writes out the name of the literal whose value matches the value of the variable.

If needed, you can explictly convert an enumeration variable to a string that represents its current value by using the built-in ToString method that all enumeration types automatically inherit from the System.Enum type. For example:

string name = colorful.ToString();  Console.WriteLine(name);      // also writes out 'Fall'

It's also possible to retrieve the underlying integer value of an enumeration variable. To do this, you must cast it to its underlying type. Remember from the discussion of unboxing in Chapter 8 that casting a type converts the data from one type to another, as long as the conversion is valid and meaningful. For example, the following code fragment will write out the value 2 and not the word Fall (Spring is 0, Summer 1, Fall 2, and Winter 3):

enum Season { Spring, Summer, Fall, Winter }  ...  Season colorful = Season.Fall;  Console.WriteLine((int)colorful); // writes out '2'

Many the standard operators that you can use on integral variables can also be used on enumeration variables (except the bitwise and shift operators, which are covered in Chapter 15, “Using Indexers”). For example, you can compare two enumeration variables of the same type for equality by using the == operator, and you can even perform arithmetic on an enumeration variable (although the result might not always be meaningful!).

Choosing Enumeration Literal Values

Each enumeration has a set of integer values associated with its elements, starting with 0 for the first element. If you prefer, you can associate a specific integer constant (such as 1) with an enumeration literal (such as Spring), as in the following example:

enum Season { Spring = 1, Summer, Fall, Winter }

IMPORTANT
The integer value that you initialize an enumeration literal with must be a compile-time constant value (such as 1). That is, it must be a constant whose value does not depend on any run-time behavior (such as a method call).

If you don't explicitly give an enumeration literal a constant integer value, the compiler gives it a value that is one more than the value of the previous enumeration literal, except for the very first enumeration literal, to which the compiler gives a default value of 0. In the previous example, the underlying values of Spring, Summer, Fall, and Winter are 1, 2, 3, and 4.

You are allowed to give more than one enumeration literal the same underlying value. For example, in the United Kingdom, Fall is referred to as Autumn. You can cater for both cultures as follows:

enum Season { Spring, Summer, Fall, Autumn = Fall, Winter }

Choosing an Enumeration's Underlying Type

When you declare an enumeration type, the enumeration literals are given values of type int. In other words, the underlying type defaults to an int. You can also choose to base your enumeration type on a different underlying integer type. For example, to declare that Season's underlying type is a short rather than an int, you can write this:

enum Season : short { Spring, Summer, Fall, Winter }

The main reason for doing this is to save memory; an int occupies more memory than a short, and if you do not need the entire range of values available to an int it can make sense to use a smaller data type.

You can base an enumeration on any of the eight integer types: byte, sbyte, short, ushort, int, uint, long, or ulong. The values of all the enumeration literals must fit inside the range of the chosen base type. For example, if you base an enumeration on the byte data type you can have a maximum of 256 literals (starting at zero).

Now that you know how to create an enumeration type, the next step is to use it.

In the following exercise, you will work with a console application to declare and use an enumeration class that represents the months of the year.

Create and use an enumeration type

  1. Start Microsoft Visual Studio 2005.

  2. Open the StructsAndEnums project, located in the \Microsoft Press\Visual CSharp Step by Step\Chapter 9\StructsAndEnums folder in your My Documents folder.

  3. In the Code and Text Editor window, display the Month.cs source file.

    The source contains an empty namespace called StructsAndEnums.

  4. Add an enumeration type called Month inside the StructsAndEnums namespace, for modeling the months of the year.

    The 12 enumeration literals for Month are January through December. The Month enumeration should look exactly like this:

    namespace StructsAndEnums  {      enum Month       {           January, February, March, April,          May, June, July, August,          September, October, November, December       }      }

  5. Display the Program.cs source file in the Code and Text Editor window.

    As in the exercises in previous chapters, the Main method calls the Entrance method and traps any exceptions that occur.

  6. In the Code and Text Editor window, add a statement to the Entrance method to declare a variable called first of type Month and initialize it to Month.January. Add another statement to write the value of the first variable to the console.

    The Entrance method should look like this:

    static void Entrance()  {      Month first = Month.January;      Console.WriteLine(first);  }

    NOTE
    When you type the period following Month, Intellisense will automatically display all the values in the Month enumeration.

  7. On the Debug menu, click Start Without Debugging.

    Visual Studio 2005 builds and runs the program. Confirm that the word ‘January' is written to the console.

  8. Press Enter to close the program and return to the Visual Studio 2005 programming environment.

  9. Add two more statements to the Entrance method to increment the first variable and display its new value to the console.

    The Entrance method should look like this:

    static void Entrance()  {      Month first = Month.January;      Console.WriteLine(first);      first++;      Console.WriteLine(first);  }

  10. On the Debug menu, click Start Without Debugging.

    Visual Studio 2005 builds and runs the program. Confirm that the words ‘January' and ‘February' are written to the console. Notice how performing a mathematical operation (such as the increment operation) on an enumeration variable changes the internal integer value of the variable. When it is displayed, the corresponding enumeration value is output.

  11. Press Enter to close the program and return to the Visual Studio 2005 programming environment.

  12. Modify the first statement in the Entrance method to initialize the first variable to Month.December.

    The Entrance method should look like this:

    static void Entrance()  {      Month first = Month.December;      Console.WriteLine(first);      first++;      Console.WriteLine(first);  }

  13. On the Debug menu, click Start Without Debugging.

    Visual Studio 2005 builds and runs the program. This time the word ‘December' is written to the console, followed by the number 12. Although you can perform arithmetic on an enumeration, if the results of the operation are outside the range of values defined for the enumerator, then all the runtime can do is treat the variable as the corresponding integer value.

  14. Press Enter to close the program and return to the Visual Studio 2005 programming environment.




Microsoft Visual C# 2005 Step by Step
Microsoft® Visual C#® 2005 Step by Step (Step By Step (Microsoft))
ISBN: B002CKYPPM
EAN: N/A
Year: 2005
Pages: 183
Authors: John Sharp

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net