- •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
84 |
Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008 |
||
Chapter 4 Quick Reference |
|
||
To |
|
Do this |
Example |
Determine whether two values |
Use the == or != operator. |
answer == 42 |
|
are equivalent |
|
|
|
|
|
|
|
Compare the value of two |
Use the <, <=, >, or >= |
Age >= 21 |
|
expressions |
operator. |
|
|
|
|
|
|
Declare a Boolean variable |
Use the bool keyword as |
bool inRange; |
|
|
|
the type of the variable. |
|
|
|
|
|
Create a Boolean expression that |
Use the && operator. |
inRange = (lo <= number) |
|
is true only if two other conditions |
|
&& (number <= hi); |
|
are true |
|
|
|
|
|
|
|
Create a Boolean expression |
Use the || operator. |
outOfRange = (number < lo) |
|
that is true if either of two other |
|
|| (hi < number); |
|
conditions is true |
|
|
|
|
|
|
|
Run a statement if a |
Use an if statement. |
If (inRange) |
|
condition is true |
|
process(); |
|
Run more than one statement if |
Use an if statement and a |
If (seconds == 59) |
|
a condition is |
block. |
{ |
|
true |
|
|
seconds = 0; |
|
|
|
minutes++; |
|
|
|
} |
Associate different |
Use a switch statement. |
switch (current) |
|
statements with different values |
|
{ |
|
of a controlling expression |
|
case 0: |
|
...
break;
case 1:
...
break; default :
...
break;
}
Chapter 5
Using Compound Assignment and
Iteration Statements
After completing this chapter, you will be able to:
Update the value of a variable by using compound assignment operators.
Write while, for, and do iteration statements.
Step through a do statement and watch as the values of variables change.
In Chapter 4, “Using Decision Statements,” you learned how to use the if and switch
constructs to run statements selectively. In this chapter, you’ll see how to use a variety of iteration (or looping) statements to run one or more statements repeatedly. When you write
iteration statements, you usually need to control the number of iterations that you perform. You can achieve this by using a variable, updating its value with each iteration, and stopping the process when the variable reaches a particular value. You’ll also learn about the special assignment operators that you should use to update the value of a variable in these circumstances.
Using Compound Assignment Operators
You’ve already seen how to use arithmetic operators to create new values. For example, the
following statement uses the plus operator (+) to display to the console a value that is 42 greater than the variable answer:
Console.WriteLine(answer + 42);
You’ve also seen how to use assignment statements to change the value of a variable. The following statement uses the assignment operator to change the value of answer to 42:
answer = 42;
If you want to add 42 to the value of a variable, you can combine the assignment operator and the addition operator. For example, the following statement adds 42 to answer. After this statement runs, the value of answer is 42 more than it was before:
answer = answer + 42;
85
86 |
Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008 |
Although this statement works, you’ll probably never see an experienced programmer write
code like this. Adding a value to a variable is so common that C# lets you perform this task in shorthand manner by using the operator +=. To add 42 to answer, you can write the following
statement:
answer += 42;
You can use this shortcut to combine any arithmetic operator with the assignment operator, as the following table shows. These operators are collectively known as the compound assignment operators.
Don’t write this |
Write this |
variable = variable * number; |
variable *= number; |
variable = variable / number; |
variable /= number; |
variable = variable % number; |
variable %= number; |
variable = variable + number; |
variable += number; |
variable = variable - number; |
variable -= number; |
Tip The compound assignment operators share the same precedence and right associativity as the simple assignment operators.
The += operator also functions on strings; it appends one string to the end of another. For example, the following code displays “Hello John” on the console:
string name = “John”; string greeting = “Hello “; greeting += name; Console.WriteLine(greeting);
You cannot use any of the other compound assignment operators on strings.
Note Use the increment (++ ) and decrement (--) operators instead of a compound assignment operator when incrementing or decrementing a variable by 1. For example, replace:
count += 1;
with
count++;
Chapter 5 Using Compound Assignment and Iteration Statements |
87 |
Writing while Statements
You use a while statement to run a statement repeatedly while some condition is true. The syntax of a while statement is as follows:
while ( booleanExpression ) statement
The Boolean expression is evaluated, and if it is true, the statement runs and then the Boolean expression is evaluated again. If the expression is still true, the statement is repeated and then the Boolean expression is evaluated again. This process continues until the Boolean expression evaluates to false, when the while statement exits. Execution then continues with the first statement after the while statement. A while statement shares many syntactic similarities with an if statement (in fact, the syntax is identical except for the keyword):
The expression must be a Boolean expression.
The Boolean expression must be written inside parentheses.
If the Boolean expression evaluates to false when first evaluated, the statement does n not run.
If you want to perform two or more statements under the control of a while statement, you must use braces to group those statements in a block.
Here’s a while statement that writes the values 0 through 9 to the console:
int i = 0; while (i < 10)
{
Console.WriteLine(i);
i++;
}
All while statements should terminate at some point. A common beginner’s mistake is forgetting to include a statement to cause the Boolean expression eventually to evaluate to false and terminate the loop, which results in a program that runs forever. In the example, the i++ statement performs this role.
Note The variable i in the while loop controls the number of iterations that it performs. This is a very common idiom, and the variable that performs this role is sometimes called the Sentinel
variable.
In the following exercise, you will write a while loop to iterate through the contents of a text file one line at a time and write each line to a text box in a form.
88 |
Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008 |
Write a while statement
1.Using Microsoft Visual Studio 2008, open the WhileStatement project, located in the \Microsoft Press\Visual CSharp Step by Step\Chapter 5\WhileStatement folder in your Documents folder.
2.On the Debug menu, click Start Without Debugging.
Visual Studio 2008 builds and runs the application. The application is a simple text file viewer that you can use to select a file and display its contents.
3.Click Open File.
The Open dialog box opens.
4.Move to the \Microsoft Press\Visual CSharp Step by Step\Chapter 5\WhileStatement\ WhileStatement folder in your Documents folder.
5.Select the file Window1.xaml.cs, and then click Open.
The name of the file, Window1.xaml.cs, appears in the small text box on the form, but the contents of the file Window1.xaml.cs do not appear in the large text box. This is because you have not yet implemented the code that reads the contents of the file and displays it. You will add this functionality in the following steps.
6.Close the form and return to Visual Studio 2008.
7.Display the code for the file Window1.xaml.cs in the Code and Text Editor window, and locate the openFileDialogFileOk method.
This method runs when the user clicks the Open button after selecting a file in the Open dialog box. The body of the method is currently implemented as follows:
private void openFileDialogFileOk(object sender, System.ComponentModel. CancelEventArgs e)
{
string fullPathname = openFileDialog.FileName; FileInfo src = new FileInfo(fullPathname); filename.Text = src.Name;
// add while loop here
}
The first statement declares a string variable called fullPathname and initializes it to the FileName property of the openFileDialog object. This property contains the full name
(including the folder) of the source file selected in the Open dialog box.
Note The openFileDialog object is an instance of the OpenFileDialog class. This class provides methods that you can use to display the standard Windows Open dialog box,
select a file, and retrieve the name and path of the selected file.
Chapter 5 Using Compound Assignment and Iteration Statements |
89 |
The second statement declares a FileInfo variable called src and initializes it to an object that represents the file selected in the Open dialog box. (FileInfo is a class provided by
the Microsoft .NET Framework that you can use to manipulate files.)
The third statement assigns the Text property of the filename control to the Name
property of the src variable. The Name property of the src variable holds the name of the file selected in the Open dialog box, but without the name of the folder. This
statement displays the name of the file in the text box on the form.
8. Replace the // add while loop here comment with the following statement:
source.Text = “”;
The source variable refers to the large text box on the form. Setting its Text property to the empty string (“”) clears any text that is currently displayed in this text box.
9.Type the following statement after the line you just added to the openFileDialogFileOk method:
TextReader reader = src.OpenText();
This statement declares a TextReader variable called reader. TextReader is another class,
provided by the .NET Framework, that you can use for reading streams of characters from sources such as files. It is located in the System.IO namespace. The FileInfo class provides the OpenText method for opening a file for reading. This statement opens the file selected by the user in the Open dialog box so that the reader variable can read the
contents of this file.
10.Add the following statement after the previous line you added to the openFileDialogFileOk method:
string line = reader.ReadLine();
This statement declares a string variable called line and calls the reader.ReadLine method to read the first line from the file into this variable. This method returns either the next line of text or a special value called null if there are no more lines to read. (If there are no lines initially, the file must be empty.)
11.Add the following statements to the openFileDialogFileOk method after the code you have just entered:
while (line != null)
{
source.Text += line + ‘\n’; line = reader.ReadLine();
}
This is a while loop that iterates through the file one line at a time until there are no more lines available.
90 Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008
The Boolean expression at the start of the while loop examines the value in the line
variable. If it is not null, the body of the loop displays the current line of text by appending it to the end of the Text property of the source text box, together with a newline character (‘\n’ —the ReadLine method of the TextReader object strips out
the newline characters as it reads each line, so the code needs to add it back in again). The while loop then reads in the next line of text before performing the next
iteration. The while loop finishes when there is no more text in the file and the ReadLine method returns a null value.
12. Add the following statement after the closing brace at the end of the while loop:
reader.Close();
This statement closes the file.
13.On the Debug menu, click Start Without Debugging.
14.When the form appears, click Open File.
15.In the Open File dialog box, move to the \Microsoft Press\Visual CSharp Step by Step\
Chapter 5\WhileStatement\WhileStatement folder in your Documents folder. Select the file Window1.xaml.cs, and then click Open.
This time the contents of the selected file appear in the text box—you should recognize the code that you have just been editing:
16.Scroll through the text in the text box, and find the openFileDialogFileOk method. Verify that this method contains the code you just added.
17.Close the form and return to the Visual Studio 2008 programming environment.
