Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
27
Добавлен:
25.03.2016
Размер:
14 Мб
Скачать
☆

Chapter 9

Creating Value Types with Enumerations and Structures

After completing this chapter, you will be able to:

Declare an enumeration type.

Create and use an enumeration type.

Declare a structure type.

Create and use a structure type.

In Chapter 8, “Understanding Values and References,” you learned about the two fundamental kinds of types that exist in Microsoft Visual C#: value types and reference types. A

value type variable holds its value directly on the stack, whereas a reference type variable holds a reference to an object on the heap. In Chapter 7, “Creating and Managing Classes and Objects,” you learned how to create your own reference types by defining classes. In this chapter, you’ll learn how to create your own value types.

C# supports two kinds of value types: enumerations and structures. We’ll look at each of them in turn.

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, if you declare an int variable named season, there is nothing to stop you from as-

signing it any legal integer value apart from 0, 1, 2, or 3. C# offers a better solution. You can create an enumeration (sometimes called an enum type), whose values are limited to a set of symbolic names.

Declaring an Enumeration

You define an enumeration by using the enum keyword, followed by a set of symbols identifying the legal values that the type can have, enclosed between braces. Here’s how to

167

168 Part II Understanding the C# Language

declare an enumeration named Season whose literal values are limited to the symbolic names

Spring, Summer, Fall, and Winter:

enum Season { Spring, Summer, Fall, Winter }

Using an Enumeration

Once you have declared an enumeration, you can use it in exactly the same way as any other type. If the name of your enumeration 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;

}

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

Season colorful = Season.Fall;

Console.WriteLine(colorful); // writes out ‘Fall’

Note Like all value types, you can create a nullable version of an enumeration variable by using the ? modifier. You can then assign the null value, as well the values defined by the enumeration,

to the variable:

Season? colorful = null;

Notice that you have to write Season.Fall rather than just Fall. All enumeration literal names are scoped by their enumeration. This is useful because it allows different enumerations 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 enumerations automatically con-

tain. For example:

Chapter 9 Creating Value Types with Enumerations and Structs

169

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

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

Choosing Enumeration Literal Values

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. It’s 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 meaning-

ful. For example, the following code example 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’

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 with which you initialize an enumeration literal must be a compile-time constant value (such as 1).

If you don’t explicitly give an enumeration literal a constant integer value, the compiler gives it a value that is 1 greater than the value of the previous enumeration literal except for the

very first enumeration literal, to which the compiler gives the default value 0. In the preceding 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 to both cultures

as follows:

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

170 Part II Understanding the C# Language

Choosing an Enumeration’s Underlying Type

When you declare an enumeration, the enumeration literals are given values of type int.

You can also choose to base your enumeration 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, using a smaller data type can make sense.

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 0).

Now that you know how to declare an enumeration, the next step is to use it. In the following exercise, you will work with a Console application to declare and use an enumeration that represents the months of the year.

Create and use an enumeration

1.Start Microsoft Visual Studio 2008 if it is not already running.

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

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

The source file contains an empty namespace named StructsAndEnums.

4.Add an enumeration named Month inside the StructsAndEnums namespace for

modeling the months of the year, as shown in bold here. The 12 enumeration literals for Month are January through December.

namespace StructsAndEnums

{

enum Month

{

January, February, March, April, May, June, July, August,

September, October, November, December

}

}

Chapter 9 Creating Value Types with Enumerations and Structs

171

5.Display the Program.cs 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 named 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 2008 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 2008 programming environment.

9.Add two more statements to the Entrance method to increment the first variable and display its new value to the console, as shown in bold here:

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 2008 builds and runs the program. Confirm that the words January and February are written to the console.

Notice that performing a mathematical operation (such as the increment operation) on an enumeration variable changes the internal integer value of the variable. When the variable is written to the console, the corresponding enumeration value is displayed.

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

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]