- •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
xxviii Introduction
Support for This Book
Every effort has been made to ensure the accuracy of this book and the contents of the companion CD. As corrections or changes are collected, they will be added to a Microsoft Knowledge Base article.
Microsoft Press provides support for books and companion CDs at the following Web site:
http://www.microsoft.com/learning/support/books/
Questions and Comments
If you have comments, questions, or ideas regarding the book or the companion CD, or questions that are not answered by visiting the site above, please send them to Microsoft Press via e-mail to
mspinput@microsoft.com
Or via postal mail to
Microsoft Press
Attn: Microsoft Visual C# 2008 Step by Step Series Editor
One Microsoft Way
Redmond, WA 98052-6399
Please note that Microsoft software product support is not offered through the above addresses.
Microsoft Visual C# 2008 Step by Step
Part I
Introducing Microsoft Visual C#
and Microsoft Visual Studio 2008
In this part:
Chapter 1. Welcome to C#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Chapter 2. Working with Variables, Operators, and Expressions . . . . . . . . . . . . . 29 Chapter 3. Writing Methods and Applying Scope. . . . . . . . . . . . . . . . . . . . . . . . . . 49 Chapter 4. Using Decision Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Chapter 5. Using Compound Assignment and Iteration Statements . . . . . . . . . . 85 Chapter 6. Managing Errors and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
1
Chapter 1
Welcome to C#
After completing this chapter, you will be able to:
Use the Microsoft Visual Studio 2008 programming environment.
Create a C# console application.
Explain the purpose of namespaces.
Create a simple graphical C# application.
Microsoft Visual C# is Microsoft’s powerful component-oriented language. C# plays an important role in the architecture of the Microsoft .NET Framework, and some people have drawn comparisons to the role that C played in the development of UNIX. If you already know a language such as C, C++, or Java, you’ll find the syntax of C# reassuringly familiar. If you are used to programming in other languages, you should soon be able to pick up the syntax and feel of C#; you just need to learn to put the braces and semicolons in the right place. Hopefully, this is just the book to help you!
In Part I, you’ll learn the fundamentals of C#. You’ll discover how to declare variables and how to use arithmetic operators such as the plus sign (+) and minus sign (–) to manipulate the
values in variables. You’ll see how to write methods and pass arguments to methods. You’ll also learn how to use selection statements such as if and iteration statements such as while.
Finally, you’ll understand how C# uses exceptions to handle errors in a graceful, easy-to-use manner. These topics form the core of C#, and from this solid foundation, you’ll progress to more advanced features in Part II through Part VI.
Beginning Programming with the Visual Studio 2008 Environment
Visual Studio 2008 is a tool-rich programming environment containing all the functionality you need to create large or small C# projects. You can even create projects that seamlessly combine modules compiled using different programming languages. In the first exercise, you start the Visual Studio 2008 programming environment and learn how to create a console application.
Note A console application is an application that runs in a command prompt window, rather than providing a graphical user interface.
3
4 |
Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008 |
Create a console application in Visual Studio 2008
If you are using Visual Studio 2008 Standard Edition or Visual Studio 2008 Professional Edition, perform the following operations to start Visual Studio 2008:
1.On the Microsoft Windows task bar, click the Start button, point to All Programs, and then point to the Microsoft Visual Studio 2008 program group.
2.In the Microsoft Visual Studio 2008 program group, click Microsoft Visual Studio 2008.
Visual Studio 2008 starts, like this:
Note If this is the first time you have run Visual Studio 2008, you might see a dialog box prompting you to choose your default development environment settings. Visual Studio 2008 can tailor itself according to your preferred development language. The various dia-
log boxes and tools in the integrated development environment (IDE) will have their default selections set for the language you choose. Select Visual C# Development Settings from the list, and then click the Start Visual Studio button. After a short delay, the Visual
Studio 2008 IDE appears.
If you are using Visual C# 2008 Express Edition, on the Microsoft Windows task bar, click the Start button, point to All Programs, and then click Microsoft Visual C# 2008 Express Edition.
Chapter 1 Welcome to C# |
5 |
Visual C# 2008 Express Edition starts, like this:
Note To avoid repetition, throughout this book, I simply state, “Start Visual Studio” when you need to open Visual Studio 2008 Standard Edition, Visual Studio 2008 Professional Edition, or Visual C# 2008 Express Edition. Additionally, unless explicitly stated, all references to Visual Studio 2008 apply to Visual Studio 2008 Standard Edition, Visual Studio 2008 Professional Edition, and Visual C# 2008 Express Edition.
If you are using Visual Studio 2008 Standard Edition or Visual Studio 2008 Professional Edition, perform the following tasks to create a new console application.
1.On the File menu, point to New, and then click Project.
The New Project dialog box opens. This dialog box lists the templates that you can use as a starting point for building an application. The dialog box categorizes templates according to the programming language you are using and the type of application.
2.In the Project types pane, click Visual C#. In the Templates pane, click the Console Application icon.
6Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008
3.In the Location field, if you are using the Windows Vista operating system, type
C:\Users\YourName\Documents\Microsoft Press\Visual CSharp Step By Step\Chapter 1. If you are using Microsoft Windows XP or Windows Server 2003, type C:\Documents and Settings\YourName\My Documents\Microsoft Press\Visual CSharp Step by Step\Chapter 1.
Replace the text YourName in these paths with your Windows user name.
Note To save space throughout the rest of this book, I will simply refer to the path “C:\ Users\YourName\Documents” or “C:\Documents and Settings\YourName\My Documents”
as your Documents folder.
Tip If the folder you specify does not exist, Visual Studio 2008 creates it for you.
4.In the Name field, type TextHello.
5.Ensure that the Create directory for solution check box is selected, and then click
OK.
If you are using Visual C# 2008 Express Edition, the New Project dialog box won’t allow you to specify the location of your project files; it defaults to the C:\Users\YourName\
AppData\Local\Temporary Projects folder. Change it by using the following procedure:
1.On the Tools menu, click Options.
2.In the Options dialog box, turn on the Show All Settings check box, and then click Projects and Solutions in the tree view in the left pane.
3.In the right pane, in the Visual Studio projects location text box, specify the
Microsoft Press\Visual CSharp Step By Step\Chapter 1 folder under your Documents folder.
4.Click OK.
If you are using Visual C# 2008 Express Edition, perform the following tasks to create a new console application.
1.On the File menu, click New Project.
2.In the New Project dialog box, click the Console Application icon.
3.In the Name field, type TextHello.
4.Click OK.
Chapter 1 Welcome to C# |
7 |
Visual Studio creates the project using the Console Application template and displays the starter code for the project, like this:
The menu bar at the top of the screen provides access to the features you’ll use in the pro-
gramming environment. You can use the keyboard or the mouse to access the menus and commands exactly as you can in all Windows-based programs. The toolbar is located beneath
the menu bar and provides button shortcuts to run the most frequently used commands. The Code and Text Editor window occupying the main part of the IDE displays the contents of
source files. In a multi-file project, when you edit more than one file, each source file has its
own tab labeled with the name of the source file. You can click the tab to bring the named source file to the foreground in the Code and Text Editor window. The Solution Explorer dis-
plays the names of the files associated with the project, among other items. You can also double-click a file name in the Solution Explorer to bring that source file to the foreground in the Code and Text Editor window.
Before writing the code, examine the files listed in the Solution Explorer, which Visual Studio 2008 has created as part of your project:
Solution ‘TextHello’ This is the top-level solution file, of which there is one per application. If you use Windows Explorer to look at your Documents\Microsoft Press\Visual CSharp Step by Step\Chapter 1\TextHello folder, you’ll see that the actual name of this file is TextHello.sln. Each solution file contains references to one or more project files.
