- •Contents at a Glance
- •Table of Contents
- •Acknowledgments
- •Introduction
- •Who This Book Is For
- •Finding Your Best Starting Point in This Book
- •System Requirements
- •Conventions and Features in This Book
- •Conventions
- •Other Features
- •Code Samples
- •Installing the Code Samples
- •Using the Code Samples
- •Support for This Book
- •Questions and Comments
- •Beginning Programming with the Visual Studio 2008 Environment
- •Writing Your First Program
- •Using Namespaces
- •Creating a Graphical Application
- •Chapter 1 Quick Reference
- •Understanding Statements
- •Identifying Keywords
- •Using Variables
- •Naming Variables
- •Declaring Variables
- •Working with Primitive Data Types
- •Displaying Primitive Data Type Values
- •Using Arithmetic Operators
- •Operators and Types
- •Examining Arithmetic Operators
- •Controlling Precedence
- •Using Associativity to Evaluate Expressions
- •Associativity and the Assignment Operator
- •Incrementing and Decrementing Variables
- •Declaring Implicitly Typed Local Variables
- •Chapter 2 Quick Reference
- •Declaring Methods
- •Specifying the Method Declaration Syntax
- •Writing return Statements
- •Calling Methods
- •Specifying the Method Call Syntax
- •Applying Scope
- •Overloading Methods
- •Writing Methods
- •Chapter 3 Quick Reference
- •Declaring Boolean Variables
- •Using Boolean Operators
- •Understanding Equality and Relational Operators
- •Understanding Conditional Logical Operators
- •Summarizing Operator Precedence and Associativity
- •Using if Statements to Make Decisions
- •Understanding if Statement Syntax
- •Using Blocks to Group Statements
- •Cascading if Statements
- •Using switch Statements
- •Understanding switch Statement Syntax
- •Following the switch Statement Rules
- •Chapter 4 Quick Reference
- •Using Compound Assignment Operators
- •Writing while Statements
- •Writing for Statements
- •Understanding for Statement Scope
- •Writing do Statements
- •Chapter 5 Quick Reference
- •Coping with Errors
- •Trying Code and Catching Exceptions
- •Handling an Exception
- •Using Multiple catch Handlers
- •Catching Multiple Exceptions
- •Using Checked and Unchecked Integer Arithmetic
- •Writing Checked Statements
- •Writing Checked Expressions
- •Throwing Exceptions
- •Chapter 6 Quick Reference
- •The Purpose of Encapsulation
- •Controlling Accessibility
- •Working with Constructors
- •Overloading Constructors
- •Understanding static Methods and Data
- •Creating a Shared Field
- •Creating a static Field by Using the const Keyword
- •Chapter 7 Quick Reference
- •Copying Value Type Variables and Classes
- •Understanding Null Values and Nullable Types
- •Using Nullable Types
- •Understanding the Properties of Nullable Types
- •Using ref and out Parameters
- •Creating ref Parameters
- •Creating out Parameters
- •How Computer Memory Is Organized
- •Using the Stack and the Heap
- •The System.Object Class
- •Boxing
- •Unboxing
- •Casting Data Safely
- •The is Operator
- •The as Operator
- •Chapter 8 Quick Reference
- •Declaring an Enumeration
- •Using an Enumeration
- •Choosing Enumeration Literal Values
- •Choosing an Enumeration’s Underlying Type
- •Working with Enumerations
- •Working with Structures
- •Declaring a Structure
- •Understanding Structure and Class Differences
- •Declaring Structure Variables
- •Understanding Structure Initialization
- •Copying Structure Variables
- •Chapter 9 Quick Reference
- •What Is an Array?
- •Declaring Array Variables
- •Creating an Array Instance
- •Initializing Array Variables
- •Creating an Implicitly Typed Array
- •Accessing an Individual Array Element
- •Iterating Through an Array
- •Copying Arrays
- •What Are Collection Classes?
- •The ArrayList Collection Class
- •The Queue Collection Class
- •The Stack Collection Class
- •The Hashtable Collection Class
- •The SortedList Collection Class
- •Using Collection Initializers
- •Comparing Arrays and Collections
- •Using Collection Classes to Play Cards
- •Chapter 10 Quick Reference
- •Using Array Arguments
- •Declaring a params Array
- •Using params object[ ]
- •Using a params Array
- •Chapter 11 Quick Reference
- •What Is Inheritance?
- •Using Inheritance
- •Base Classes and Derived Classes
- •Calling Base Class Constructors
- •Assigning Classes
- •Declaring new Methods
- •Declaring Virtual Methods
- •Declaring override Methods
- •Understanding protected Access
- •Understanding Extension Methods
- •Chapter 12 Quick Reference
- •Understanding Interfaces
- •Interface Syntax
- •Interface Restrictions
- •Implementing an Interface
- •Referencing a Class Through Its Interface
- •Working with Multiple Interfaces
- •Abstract Classes
- •Abstract Methods
- •Sealed Classes
- •Sealed Methods
- •Implementing an Extensible Framework
- •Summarizing Keyword Combinations
- •Chapter 13 Quick Reference
- •The Life and Times of an Object
- •Writing Destructors
- •Why Use the Garbage Collector?
- •How Does the Garbage Collector Work?
- •Recommendations
- •Resource Management
- •Disposal Methods
- •Exception-Safe Disposal
- •The using Statement
- •Calling the Dispose Method from a Destructor
- •Making Code Exception-Safe
- •Chapter 14 Quick Reference
- •Implementing Encapsulation by Using Methods
- •What Are Properties?
- •Using Properties
- •Read-Only Properties
- •Write-Only Properties
- •Property Accessibility
- •Understanding the Property Restrictions
- •Declaring Interface Properties
- •Using Properties in a Windows Application
- •Generating Automatic Properties
- •Initializing Objects by Using Properties
- •Chapter 15 Quick Reference
- •What Is an Indexer?
- •An Example That Doesn’t Use Indexers
- •The Same Example Using Indexers
- •Understanding Indexer Accessors
- •Comparing Indexers and Arrays
- •Indexers in Interfaces
- •Using Indexers in a Windows Application
- •Chapter 16 Quick Reference
- •Declaring and Using Delegates
- •The Automated Factory Scenario
- •Implementing the Factory Without Using Delegates
- •Implementing the Factory by Using a Delegate
- •Using Delegates
- •Lambda Expressions and Delegates
- •Creating a Method Adapter
- •Using a Lambda Expression as an Adapter
- •The Form of Lambda Expressions
- •Declaring an Event
- •Subscribing to an Event
- •Unsubscribing from an Event
- •Raising an Event
- •Understanding WPF User Interface Events
- •Using Events
- •Chapter 17 Quick Reference
- •The Problem with objects
- •The Generics Solution
- •Generics vs. Generalized Classes
- •Generics and Constraints
- •Creating a Generic Class
- •The Theory of Binary Trees
- •Building a Binary Tree Class by Using Generics
- •Creating a Generic Method
- •Chapter 18 Quick Reference
- •Enumerating the Elements in a Collection
- •Manually Implementing an Enumerator
- •Implementing the IEnumerable Interface
- •Implementing an Enumerator by Using an Iterator
- •A Simple Iterator
- •Chapter 19 Quick Reference
- •What Is Language Integrated Query (LINQ)?
- •Using LINQ in a C# Application
- •Selecting Data
- •Filtering Data
- •Ordering, Grouping, and Aggregating Data
- •Joining Data
- •Using Query Operators
- •Querying Data in Tree<TItem> Objects
- •LINQ and Deferred Evaluation
- •Chapter 20 Quick Reference
- •Understanding Operators
- •Operator Constraints
- •Overloaded Operators
- •Creating Symmetric Operators
- •Understanding Compound Assignment
- •Declaring Increment and Decrement Operators
- •Implementing an Operator
- •Understanding Conversion Operators
- •Providing Built-In Conversions
- •Creating Symmetric Operators, Revisited
- •Adding an Implicit Conversion Operator
- •Chapter 21 Quick Reference
- •Creating a WPF Application
- •Creating a Windows Presentation Foundation Application
- •Adding Controls to the Form
- •Using WPF Controls
- •Changing Properties Dynamically
- •Handling Events in a WPF Form
- •Processing Events in Windows Forms
- •Chapter 22 Quick Reference
- •Menu Guidelines and Style
- •Menus and Menu Events
- •Creating a Menu
- •Handling Menu Events
- •Shortcut Menus
- •Creating Shortcut Menus
- •Windows Common Dialog Boxes
- •Using the SaveFileDialog Class
- •Chapter 23 Quick Reference
- •Validating Data
- •Strategies for Validating User Input
- •An Example—Customer Information Maintenance
- •Performing Validation by Using Data Binding
- •Changing the Point at Which Validation Occurs
- •Chapter 24 Quick Reference
- •Querying a Database by Using ADO.NET
- •The Northwind Database
- •Creating the Database
- •Using ADO.NET to Query Order Information
- •Querying a Database by Using DLINQ
- •Creating and Running a DLINQ Query
- •Deferred and Immediate Fetching
- •Joining Tables and Creating Relationships
- •Deferred and Immediate Fetching Revisited
- •Using DLINQ to Query Order Information
- •Chapter 25 Quick Reference
- •Using Data Binding with DLINQ
- •Using DLINQ to Modify Data
- •Updating Existing Data
- •Adding and Deleting Data
- •Chapter 26 Quick Reference
- •Understanding the Internet as an Infrastructure
- •Understanding Web Server Requests and Responses
- •Managing State
- •Understanding ASP.NET
- •Creating Web Applications with ASP.NET
- •Building an ASP.NET Application
- •Understanding Server Controls
- •Creating and Using a Theme
- •Chapter 27 Quick Reference
- •Comparing Server and Client Validations
- •Validating Data at the Web Server
- •Validating Data in the Web Browser
- •Implementing Client Validation
- •Chapter 28 Quick Reference
- •Managing Security
- •Understanding Forms-Based Security
- •Implementing Forms-Based Security
- •Querying and Displaying Data
- •Understanding the Web Forms GridView Control
- •Displaying Customer and Order History Information
- •Paging Data
- •Editing Data
- •Updating Rows Through a GridView Control
- •Navigating Between Forms
- •Chapter 29 Quick Reference
- •What Is a Web Service?
- •The Role of SOAP
- •What Is the Web Services Description Language?
- •Nonfunctional Requirements of Web Services
- •The Role of Windows Communication Foundation
- •Building a Web Service
- •Creating the ProductsService Web Service
- •Web Services, Clients, and Proxies
- •Talking SOAP: The Easy Way
- •Consuming the ProductsService Web Service
- •Chapter 30 Quick Reference
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.
