- •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
78Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008
16.Click Compare.
The following text appears in the text box:
first == second : False first != second : True first < second : True first <= second : True first > second : False first >= second : False
Again, these are the correct results when the first date is earlier than the second date.
17.Test some other dates, and verify that the results are as you would expect. Click Quit when you have finished.
Comparing Dates in Real-World Applications
Now that you have seen how to use a rather long and complicated series of if and else statements, I should mention that this is not the technique you would use to com-
pare dates in a real-world application. In the Microsoft .NET Framework class library, dates are held using a special type called DateTime. If you look at the dateCompare
method you have written in the preceding exercise, you will see that the two parameters, leftHandSide and rightHandSide, are DateTime values. The logic you have written
compares only the date part of these variables—there is also a time element. For two DateTime values to be considered equal, they should not only have the same date but
also the same time. Comparing dates and times is such a common operation that the DateTime type has a built-in method called Compare for doing just that. The Compare method takes two DateTime arguments and compares them, returning a value indicat-
ing whether the first argument is less than the second, in which case the result will be negative; whether the first argument is greater than the second, in which case the result will be positive; or whether both arguments represent the same date and time, in which case the result will be 0.
Using switch Statements
Sometimes when you write a cascading if statement, all the if statements look similar because they all evaluate an identical expression. The only difference is that each if compares the result of the expression with a different value. For example, consider the following block of
Chapter 4 Using Decision Statements |
79 |
code that uses an if statement to examine the value in the day variable and work out which day of the week it is:
if (day == 0)
dayName = “Sunday”; else if (day == 1)
dayName = “Monday”; else if (day == 2)
dayName = “Tuesday”; else if (day == 3)
...
else
dayName = “Unknown”;
In these situations, often you can rewrite the cascading if statement as a switch statement to make your program more efficient and more readable.
Understanding switch Statement Syntax
The syntax of a switch statement is as follows (switch, case, and default are keywords):
switch ( controllingExpression )
{
case constantExpression : statements
break;
case constantExpression : statements
break;
...
default : statements break;
}
The controllingExpression is evaluated once. Control then jumps to the block of code identified by the constantExpression whose value is equal to the result of the controllingExpression. (The identifier is called a case label.) Execution runs as far as the break statement, at which point the switch statement finishes and the program continues at the first statement after the closing brace of the switch statement. If none of the constantExpression values are equal to the value of the controllingExpression, the statements below the optional default label run.
Note Each constantExpression value must be unique, so the controllingExpression will match only one of them. If the value of the controllingExpression does not match any constantExpression value, and there is no default label, program execution continues with the first statement after the closing brace of the switch statement.
80 Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008
For example, you can rewrite the previous cascading if statement as the following switch statement:
switch (day)
{
case 0 :
dayName = “Sunday”; break;
case 1 :
dayName = “Monday”; break;
case 2 :
dayName = “Tuesday”; break;
...
default :
dayName = “Unknown”; break;
}
Following the switch Statement Rules
The switch statement is very useful, but unfortunately, you can’t always use it when you may like to. Any switch statement you write must adhere to the following rules:
You can use switch only on primitive data types, such as int or string. With any other types (including float and double), you’ll have to use an if statement.
The case labels must be constant expressions, such as 42 or “42”. If you need to calculate your case label values at run time, you must use an if statement.
The case labels must be unique expressions. In other words, two case labels cannot have the same value.
You can specify that you want to run the same statements for more than one value by providing a list of case labels and no intervening statements, in which case the code for the final label in the list is executed for all cases in that list. However, if a label has one or more associated statements, execution cannot fall through to subsequent labels, and the compiler generates an error. For example:
switch (trumps) |
|
{ |
|
case Hearts : |
// Fall-through allowed – no code between labels |
case Diamonds : |
|
color = "Red"; |
// Code executed for Hearts and Diamonds |
break; |
|
case Clubs : |
|
color = "Black"; |
// Error – code between labels |
case Spades : |
|
color = "Black"; |
|
break; |
|
} |
|
Chapter 4 Using Decision Statements |
81 |
Note The break statement is the most common way to stop fall-through, but you can also use a return statement or a throw statement. The throw statement is described in Chapter 6,
“Managing Errors and Exceptions.”
switch Fall-Through Rules
Because you cannot accidentally fall through from one case label to the next if there is any intervening code, you can freely rearrange the sections of a switch statement without affecting its meaning (including the default label, which by convention is usually
placed as the last label but does not have to be).
C and C++ programmers should note that the break statement is mandatory for every case in a switch statement (even the default case). This requirement is a good thing; it is
very common in C or C++ programs to forget the break statement, allowing execution to fall through to the next label and leading to bugs that are very difficult to spot.
If you really want to, you can mimic C/C++ fall-through in C# by using a goto statement to go to the following case or default label. Using goto in general is not recommended,
though, and this book does not show you how to do it!
In the following exercise, you will complete a program that reads the characters of a string and maps each character to its XML representation. For example, the left angle bracket character, <, has a special meaning in XML (it’s used to form elements). If you have data that contains this character, it must be translated into the text “<” so that an XML processor knows that it is data and not part of an XML instruction. Similar rules apply to the right angle
bracket (>), ampersand (&), single quotation mark (‘), and double quotation mark (“) characters. You will write a switch statement that tests the value of the character and traps the
special XML characters as case labels.
Write switch statements
1.Start Visual Studio 2008 if it is not already running.
2.Open the SwitchStatement project, located in the \Microsoft Press\Visual CSharp Step by Step\Chapter 4\SwitchStatement folder in your Documents folder.
3.On the Debug menu, click Start Without Debugging.
Visual Studio 2008 builds and runs the application. The application displays a form containing two text boxes separated by a Copy button.
82 |
Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008 |
4. Type the following sample text into the upper text box:
inRange = (lo <= number) && (hi >= number);
5.Click Copy.
The statement is copied verbatim into the lower text box, and no translation of the <, &, or > character occurs.
6.Close the form, and return to Visual Studio 2008.
7.Display the code for Window1.xaml.cs in the Code and Text Editor window, and locate the copyOne method.
The copyOne method copies the character specified as its input parameter to the end of the text displayed in the lower text box. At the moment, copyOne contains a switch statement with a single default section. In the following few steps, you will modify this switch statement to convert characters that are significant in XML to their XML mapping. For example, the < character will be converted to the string “<”.
8.Add the following statements to the switch statement after the opening brace for the statement and directly before the default label:
case ‘<’ :
target.Text += “<”; break;
If the current character being copied is a >, this code will append the string “<” to the text being output in its place.
9.Add the following statements to the switch statement after the break statement you have just added and above the default label:
case ‘>’ :
target.Text += “>”; break;
case ‘&’ :
target.Text += “&”; break;
Chapter 4 Using Decision Statements |
83 |
case ‘\”’ :
target.Text += “"”; break;
case ‘\’’ :
target.Text += “'”; break;
Note The single quotation mark (‘) and double quotation mark (“) have a special meaning
in C# as well as in XML—they are used to delimit character and string constants. The backslash (\) in the final two case labels is an escape character that causes the C# compiler to
treat these characters as literals rather than as delimiters.
10.On the Debug menu, click Start Without Debugging.
11.Type the following text into the upper text box:
inRange = (lo <= number) && (hi >= number);
12.Click Copy.
The statement is copied into the lower text box. This time, each character undergoes the XML mapping implemented in the switch statement. The target text box displays the following text:
inRange = (lo <= number) && (hi >= number)
13.Experiment with other strings, and verify that all special characters (<, >, &, “, and ‘) are handled correctly.
14.Close the form.
If you want to continue to the next chapter
Keep Visual Studio 2008 open, and turn to Chapter 5. 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.
