- •Contents at a Glance
- •Table of Contents
- •Acknowledgments
- •Introduction
- •Who This Book Is For
- •Finding Your Best Starting Point in This Book
- •Conventions and Features in This Book
- •Conventions
- •Other Features
- •System Requirements
- •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
- •Working with Enumerations
- •Declaring an Enumeration
- •Using an Enumeration
- •Choosing Enumeration Literal Values
- •Choosing an Enumeration’s Underlying Type
- •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 5 Using Compound Assignment and Iteration Statements |
93 |
Second, you can write next to each other two or more for statements that reuse the same variable name because each variable is in a different scope. Here’s an example:
for (int i = 0; i < 10; i++)
{
...
}
for (int i = 0; i < 20; i += 2) // okay
{
...
}
Writing do Statements
The while and for statements both test their Boolean expression at the start of the loop. This means that if the expression evaluates to false on the very first test, the body of the loop
does not run, not even once. The do statement is different; its Boolean expression is evaluated after each iteration, so the body always executes at least once.
The syntax of the do statement is as follows (don’t forget the final semicolon):
do
statement
while (booleanExpression);
You must use a statement block if the body of the loop comprises more than one statement. Here’s a version of the example that writes the values 0 through 9 to the console, this time constructed using a do statement:
int i = 0; do
{
Console.WriteLine(i);
i++;
}
while (i < 10);
94 |
Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008 |
The break and continue Statements
In Chapter 4, you saw the break statement being used to jump out of a switch statement. You can also use a break statement to jump out of the body of an iteration
statement. When you break out of a loop, the loop exits immediately and execution continues at the first statement after the loop. Neither the update nor the continuation condition of the loop is rerun.
In contrast, the continue statement causes the program to perform the next iteration of the loop immediately (after reevaluating the Boolean expression). Here’s another ver-
sion of the example that writes the values 0 through 9 to the console, this time using break and continue statements:
int i = 0; while (true)
{
Console.WriteLine(“continue “ + i); i++;
if (i < 10) continue;
else
break;
}
This code is absolutely ghastly. Many programming guidelines recommend using continue cautiously or not at all because it is often associated with hard-to-under- stand code. The behavior of continue is also quite subtle. For example, if you execute a continue statement from inside a for statement, the update part runs before
performing the next iteration of the loop.
In the following exercise, you will write a do statement to convert a positive whole number to its string representation in octal notation.
Examine a do statement
1.Using Visual Studio 2008, open the DoStatement project, located in the \Microsoft Press\Visual CSharp Step by Step\Chapter 5\DoStatement folder in your Documents folder.
2.On the Debug menu, click Start Without Debugging.
The application displays a form that has two text boxes and a button called Show Steps.
When you type a positive integer (the program doesn’t work with negative integers) in the upper text box and click Show Steps, the program takes the number that you have typed in and converts it to a string representing the octal (base 8) value of the same
Chapter 5 Using Compound Assignment and Iteration Statements |
95 |
number. The program uses a well-known algorithm that repeatedly divides a number by 8, calculating the remainder at each stage. The lower text box shows the steps used to build this octal presentation.
3.Type 2693 in the upper text box, and then click Show Steps.
The lower text box displays the steps used to create the octal representation of 2693 (5205):
4.Close the window to return to the Visual Studio 2008 programming environment.
5.Display the code for Window1.xaml.cs in the Code and Text Editor window.
6.Locate the showStepsClick method. This method runs when the user clicks the Show Steps button on the form.
This method contains the following statements:
int amount = int.Parse(number.Text); steps.Text = “”;
string current = “”; do
{
int nextDigit = amount % 8;
int digitCode = ‘0’ + nextDigit;
char digit = Convert.ToChar(digitCode); current = digit + current;
steps.Text += current + “\n”; amount /= 8;
}
while (amount != 0);
The first statement converts the string value in the Text property of the number text box into an int using the Parse method of the int type:
int amount = int.Parse(number.Text);
96 Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008
The second statement clears the text displayed in the lower text box (called steps) by setting its Text property to the empty string:
steps.Text = “”;
The third statement declares a string variable called current and initializes it to the empty string:
string current = “”;
The real work in this method is performed by the do statement, which begins at the fourth statement:
do
{
...
}
while (amount != 0);
The algorithm repeatedly performs integer arithmetic to divide the amount variable by
8 and determine the remainder; the remainder after each successive division constitutes the next digit in the string being built. Eventually, when amount is reduced to 0, the
loop finishes. Notice that the body must run at least once. This behavior is exactly what is required because even the number 0 has one octal digit.
Look more closely at the code, and you will see that the first statement inside the do loop is this:
int nextDigit = amount % 8;
This statement declares an int variable called nextDigit and initializes it to the remainder after dividing the value in amount by 8. This will be a number somewhere between 0
and 7.
The next statement is this:
int digitCode = ‘0’ + nextDigit;
This statement requires a little explanation! Characters have a unique code according to the character set used by the operating system. In the character sets frequently used by the Microsoft Windows operating system, the code for character ‘0’ has integer value 48. The code for character ‘1’ is 49, the code for character ‘2’ is 50, and so on up to the code for character ‘9’, which has integer value 57. C# allows you to treat a character as an integer and perform arithmetic on it, but when you do so, C# uses the character’s
code as the value. So the expression ‘0’ + nextDigit will actually result in a value somewhere between 48 and 55 (remember that nextDigit will be between 0 and 7),
corresponding to the code for the equivalent octal digit. The third statement inside the do loop is
char digit = Convert.ToChar(digitCode);
Chapter 5 Using Compound Assignment and Iteration Statements |
97 |
This statement declares a char variable called digit and initializes it to the result of the
Convert.ToChar(digitCode) method call. The Convert.ToChar method takes an integer
holding a character code and returns the corresponding character. So, for example, if digitCode has the value 54, Convert.ToChar(digitCode) will return the character ‘6’.
To summarize, the first three statements in the do loop have determined the character representing the least-significant (rightmost) octal digit corresponding to the number the user typed in. The next task is to prepend this digit to the string being output, like this:
current = digit + current;
The next statement inside the do loop is this:
steps.Text += current + “\n”;
This statement adds to the Steps text box the string containing the digits produced so far for the octal representation of the number.
The final statement inside the do loop is
amount /= 8;
This is a compound assignment statement and is equivalent to writing amount = amount / 8;. If the value of amount is 2693, the value of amount after this statement
runs is 336.
Finally, the condition in the while clause at the end of the loop is evaluated:
while (amount != 0)
Because the value of amount is not yet 0, the loop performs another iteration.
In the final exercise, you will use the Visual Studio 2008 debugger to step through the previous do statement to help you understand how it works.
Step through the do statement
1.In the Code and Text Editor window displaying the Window1.xaml.cs file, move the cursor to the first statement of the showStepsClick method:
int amount = int.Parse(number.Text);
2.Right-click anywhere in the first statement, and then click Run To Cursor.
3.When the form appears, type 2693 in the upper text box, and then click Show Steps.
The program stops, and you are placed in Visual Studio 2008 in debug mode. A yellow arrow in the left margin of the Code and Text Editor window indicates the current statement.
98Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008
4.Display the Debug toolbar if it is not visible. (On the View menu, point to Toolbars, and then click Debug.)
5.On the Debug toolbar, click the Windows drop-down arrow.
Note The Windows icon is the rightmost icon in the Debug toolbar.
The following menu appears:
Note If you are using Microsoft Visual C# 2008 Express Edition, the shortcut menu that appears contains a subset of those shown in the following image.
6.On the drop-down menu, click Locals.
The Locals window appears (if it wasn’t already open). This window displays the name, value, and type of the local variables in the current method, including the amount local variable. Notice that the value of amount is currently 0:
Chapter 5 Using Compound Assignment and Iteration Statements |
99 |
7.On the Debug toolbar, click the Step Into button. The debugger runs the statement:
int amount = int.Parse(number.Text);
The value of amount in the Locals window changes to 2693, and the yellow arrow moves to the next statement.
8.Click Step Into again.
The debugger runs the statement:
steps.Text = “”;
This statement does not affect the Locals window because steps is a control on the form and not a local variable. The yellow arrow moves to the next statement.
9.Click Step Into.
The debugger runs the statement:
string current = “”;
The yellow arrow moves to the opening brace at the start of the do loop.
10.Click Step Into.
The yellow arrow moves to the first statement inside the do loop. The do loop contains three local variables of its own: nextDigit, digitCode, and digit. Notice that these local variables appear in the Locals window, and that the value of all three variables is 0.
11.Click Step Into.
The debugger runs the statement:
int nextDigit = amount % 8;
The value of nextDigit in the Locals window changes to 5. This is the remainder after dividing 2693 by 8.
12.Click Step Into.
The debugger runs the statement:
int digitCode = ‘0’ + nextDigit;
The value of digitCode in the Locals window changes to 53. This is the character code of ‘5’ (48 + 5).
100Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008
13.Click Step Into.
The debugger runs the statement:
char digit = Convert.ToChar(digitCode);
The value of digit changes to ‘5’ in the Locals window. The Locals window shows char values using both the underlying numeric value (in this case, 53) and also the character representation (‘5’).
Note that in the Locals window, the value of the current variable is “”.
14.Click Step Into.
The debugger runs the statement:
current = current + digit;
The value of current changes to “5” in the Locals window.
15.Click Step Into.
The debugger runs the statement:
steps.Text += current + “\n”;
This statement displays the text “5” in the steps text box, followed by a newline character to cause subsequent output to be displayed on the next line in the text box. (The form is currently hidden behind Visual Studio, so you won’t be able to see it.)
16.Click Step Into.
The debugger runs the statement:
amount /= 8;
The value of amount changes to 336 in the Locals window. The yellow arrow moves to the brace at the end of the do loop.
17.Click Step Into.
The yellow arrow moves to the while statement.
18.Click Step Into.
The debugger runs the statement:
while (amount != 0);
The value of amount is 336, and the expression 336 != 0 evaluates to true, so the do loop performs another iteration. The yellow arrow jumps back to the opening brace at the start of the do loop.
19.Click Step Into.
The yellow arrow moves to the first statement inside the do loop again.
Chapter 5 Using Compound Assignment and Iteration Statements |
101 |
20.Repeatedly click Step Into to step through the next three iterations of the do loop, and watch how the values of the variables change in the Locals window.
21.At the end of the fourth iteration of the loop, the value of amount is now 0 and the value of current is “5205”. The yellow arrow is on the continuation condition of the do loop:
while (amount != 0);
The value of amount is now 0, so the expression amount != 0 will evaluate to false, and the do loop will terminate.
22.Click Step Into.
The debugger runs the statement:
while (amount != 0);
As predicted, the do loop terminates, and the yellow arrow moves to the closing brace at the end of the showStepsClick method.
23.Click the Continue button on the Debug toolbar.
The form appears, displaying the four steps used to create the octal representation of 2693: “5”, “05”, “205”, and “5205”.
24.Close the form to return to the Visual Studio 2008 programming environment.
Congratulations! You have successfully written meaningful while and do statements and used the Visual Studio 2008 debugger to step through the do statement.
If you want to continue to the next chapter
Keep Visual Studio 2008 running, and turn to Chapter 6.
If you want to exit Visual Studio 2008 now
On the File menu, click Exit. If you see a Save dialog box, click Yes (if you are using Visual Studio 2008) or Save (if you are using Visual C# 2008 Express Edition) and save the project.
