- •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
38Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008
8.Select the int type in the Choose a data type list. Confirm that the value 42 is displayed in the Sample value text box.
9.Click Quit to close the window and stop the program.
10.In the Code and Text Editor window, find the showDoubleValue method.
11.Edit the showDoubleValue method exactly as shown in bold type in the following code:
private void showDoubleValue()
{
double variable; variable = 0.42; value.Text = “0.42”;
}
12.In the Code and Text Editor window, locate the showBoolValue method.
13.Edit the showBoolValue method exactly as follows:
private void showBoolValue()
{
bool variable; variable = false; value.Text = “false”;
}
14.On the Debug menu, click Start Without Debugging.
15.In the Choose a data type list, select the int, double, and bool types. In each case, verify that the correct value is displayed in the Sample value text box.
16.Click Quit to stop the program.
Using Arithmetic Operators
C# supports the regular arithmetic operations you learned in your childhood: the plus sign
(+) for addition, the minus sign (–) for subtraction, the asterisk (*) for multiplication, and the forward slash (/) for division. The symbols +, –, *, and / are called operators because they “operate” on values to create new values. In the following example, the variable moneyPaidToConsultant ends up holding the product of 750 (the daily rate) and 20 (the number of days
the consultant was employed):
long moneyPaidToConsultant; moneyPaidToConsultant = 750 * 20;
Chapter 2 Working with Variables, Operators, and Expressions |
39 |
Note The values that an operator operates on are called operands. In the expression 750 * 20, the * is the operator, and 750 and 20 are the operands.
Operators and Types
Not all operators are applicable to all data types. The operators that you can use on a value
depend on the value’s type. For example, you can use all the arithmetic operators on values of type char, int, long, float, double, or decimal. However, with the exception of the plus operator, +, you can’t use the arithmetic operators on values of type string or bool. So the following statement is not allowed because the string type does not support the minus operator
(subtracting one string from another would be meaningless):
// compile-time error
Console.WriteLine(“Gillingham” – “Forest Green Rovers”);
You can use the + operator to concatenate string values. You need to be careful because this can have results you might not expect. For example, the following statement writes “431” (not “44”) to the console:
Console.WriteLine(“43” + “1”);
Tip The .NET Framework provides a method called Int32.Parse that you can use to convert a string value to an integer if you need to perform arithmetic computations on values held as strings.
You should also be aware that the type of the result of an arithmetic operation depends on
the type of the operands used. For example, the value of the expression 5.0/2.0 is 2.5; the type of both operands is double (in C#, literal numbers with decimal points are always double, not float, to maintain as much accuracy as possible), so the type of the result is also double.
However, the value of the expression 5/2 is 2. In this case, the type of both operands is int, so the type of the result is also int. C# always rounds values down in circumstances like this. The
situation gets a little more complicated if you mix the types of the operands. For example, the expression 5/2.0 consists of an int and a double. The C# compiler detects the mismatch and generates code that converts the int into a double before performing the operation. The
result of the operation is therefore a double (2.5). However, although this works, it is considered poor practice to mix types in this way.
40 |
Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008 |
Numeric Types and Infinite Values
There are one or two other features of numbers in C# that you should be aware of. For
example, the result of dividing any number by zero is infinity, which is outside the range of the int, long, and decimal types, and consequently evaluating an expression such as 5/0 results in an error. However, the double and float types actually have a special value that can represent infinity, and the value of the expression 5.0/0.0 is Infinity. The one
exception to this rule is the value of the expression 0.0/0.0. Usually, if you divide zero by anything, the result is zero, but if you divide anything by zero the result is infinity. The expression 0.0/0.0 results in a paradox—the value must be zero and infinity at the
same time. C# has another special value for this situation called NaN, which stands for “not a number.” So if you evaluate 0.0/0.0, the result is NaN. NaN and Infinity propagate
through expressions. If you evaluate 10 + NaN, the result is NaN, and if you evaluate 10 + Infinity, the result is Infinity. The one exception to this rule is the expression Infinity *
0, which results in 0, whereas the result of the expression NaN * 0 is NaN.
C# also supports one less-familiar arithmetic operator: the remainder, or modulus, operator, which is represented by the percent sign (%). The result of x % y is the remainder after dividing x by y. For example, 9 % 2 is 1 because 9 divided by 2 is 4, remainder 1.
Note If you are familiar with C or C++, you will know that you can’t use the remainder operator on float or double values in these languages. However, C# relaxes this rule. The remainder
operator is valid with all numeric types, and the result is not necessarily an integer. For example, the result of the expression 7.0 % 2.4 is 2.2.
Examining Arithmetic Operators
The following exercise demonstrates how to use the arithmetic operators on int values using a previously written C# program called MathsOperators.
Work with arithmetic operators
1.Open the MathsOperators project, located in the \Microsoft Press\Visual CSharp Step by Step\Chapter 2\MathsOperators folder in your Documents folder.
2.On the Debug menu, click Start Without Debugging. A form appears on the screen.
3.Type 54 in the left operand text box.
Chapter 2 Working with Variables, Operators, and Expressions |
41 |
4.Type 13 in the right operand text box.
You can now apply any of the operators to the values in the text boxes.
5.Click the – Subtraction button, and then click Calculate.
The text in the Expression text box changes to 54 – 13, and the value 41 appears in the Result box, as shown in the following image:
6.Click the / Division button, and then click Calculate.
The text in the Expression text box changes to 54/13, and the value 4 appears in the Result text box. In real life, 54/13 is 4.153846 recurring, but this is not real life; this is C# performing integer division, and when you divide one integer by another integer, the answer you get back is an integer, as explained earlier.
7.Click the % Remainder button, and then click Calculate.
The text in the Expression text box changes to 54 % 13, and the value 2 appears in the Result text box. This is because the remainder after dividing 54 by 13 is 2. (54 – ((54/13) * 13) is 2 if you do the arithmetic rounding down to an integer at each stage—my old math master at school would be horrified to be told that (54/13) * 13 does not equal 54!)
8.Test the other combinations of numbers and operators. When you have finished, click Quit to return to the Visual Studio 2008 programming environment.
Now take a look at the MathsOperators program code.
42 |
Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008 |
Examine the MathsOperators program code
1.Display the Window1.xaml form in the Design View window (double-click the file
Window1.xaml in Solution Explorer).
2.On the View menu, point to Other Windows, and then click Document Outline.
The Document Outline window appears, showing the names and types of the controls
on the form. If you click each of the controls on the form, the name of the control is highlighted in the Document Outline window. Similarly, if you select a control in the Document Outline window, the corresponding control is selected in the Design View window.
3.On the form, click the two TextBox controls in which the user types numbers. In the
Document Outline window, verify that they are named lhsOperand and rhsOperand.
(You can see the name of a control in the parentheses to the right of the control.)
When the form runs, the Text property of each of these controls holds the values that the user enters.
4.Toward the bottom of the form, verify that the TextBox control used to display the expression being evaluated is named expression and that the TextBox control used to display the result of the calculation is named result.
5.Close the Document Outline window.
6.Display the code for the Window1.xaml.cs file in the Code and Text Editor window.
7.In the Code and Text Editor window, locate the subtractValues method. It looks like this:
private void subtractValues()
{
int lhs = int.Parse(lhsOperand.Text); int rhs = int.Parse(rhsOperand.Text); int outcome;
outcome = lhs – rhs;
expression.Text = lhsOperand.Text + “ – “ + rhsOperand.Text; result.Text = outcome.ToString();
}
The first statement in this method declares an int variable called lhs and initializes it with the integer corresponding to the value typed by the user in the lhsOperand text
box. Remember that the Text property of a text box control contains a string, so you
must convert this string to an integer before you can assign it to an int variable. The int data type provides the int.Parse method, which does precisely this.
The second statement declares an int variable called rhs and initializes it to the value in the rhsOperand text box after converting it to an int.
The third statement declares an int variable called outcome.
