Chapters 24–35 and Appendices D–G are PDF documents posted online at the book’s Companion Website located at www.pearsonhighered.com/deitel/ .1 Introduction to Computers, the Internet 1.
Trang 5D e i t e l ® S e r i e s P a g eHow To Program Series
Android How to Program
C How to Program, 7/E
C++ How to Program, 9/E
C++ How to Program, Late Objects Version, 7/E
Java™ How to Program, 9/E
Java™ How to Program, Late Objects Version, 8/E
Internet & World Wide Web How to Program, 5/E
Visual Basic®2012 How to Program
Visual C#®2012 How to Program, 5/E
Visual C++®2008 How to Program, 2/E
Small Java™ How to Program, 6/E
Small C++ How to Program, 5/E
Simply Series
Simply C++: An App-Driven Tutorial Approach
Simply Java™ Programming: An App-Driven
C++ How to Program, 7/E, 8/E & 9/E
Simply C++: An App-Driven Tutorial Approach
Java™ How to Program, 7/E, 8/E & 9/E
Simply Visual Basic 2010: An App-DrivenApproach, 4/E
Visual Basic®2012 How to ProgramVisual Basic®2010 How to ProgramVisual C#®2012 How to Program, 5/EVisual C#®2010 How to Program, 4/E
Deitel® Developer Series
C++ for Programmers, 2/EAndroid for Programmers: An App-DrivenApproach
C# 2010 for Programmers, 3/EDive Into®iOS 6: An App-Driven ApproachiOS 6 for Programmers: An App-Driven ApproachJava™ for Programmers, 2/E
JavaScript for Programmers
LiveLessons Video Learning Products
www.deitel.com/books/LiveLessons/Android®App Development FundamentalsC++ Fundamentals
C# FundamentalsiOS 6 App Development FundamentalsJava™ Fundamentals
JavaScript FundamentalsVisual Basic®Fundamentals
To receive updates on Deitel publications, Resource Centers, training courses, partner offers and more,
please register for the free Deitel ® Buzz Online e-mail newsletter at:
For information on government and corporate Dive-Into ® Series on-site seminars offered by Deitel &
Associates, Inc worldwide, visit:
Trang 7Associate Editor: Carole Snyder
Director of Marketing: Christy Lesko
Marketing Manager: Yezan Alayan
Marketing Assistant: Jon Bryant
Director of Production: Erin Gregg
Managing Editor: Scott Disanno
Associate Managing Editor: Robert Engelhardt
Operations Specialist: Lisa McDowell
Art Director: Anthony Gemmellaro
Cover Design: Abbey S Deitel, Harvey M Deitel, Anthony Gemmellaro
Cover Photo Credit: © Shutterstock/Excellent backgrounds
Media Project Manager: Renata Butera
Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear
on page vi.
The authors and publisher of this book have used their best efforts in preparing this book These efforts include the development, research, and testing of the theories and programs to determine their effectiveness The authors and pub- lisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in this book The authors and publisher shall not be liable in any event for incidental or consequential dam- ages in connection with, or arising out of, the furnishing, performance, or use of these programs.
Copyright © 2014, 2011, 2009 Pearson Education, Inc., publishing as Prentice Hall All rights reserved tured in the United States of America This publication is protected by Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or
Manufac-by any means, electronic, mechanical, photocopying, recording, or likewise To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to 201-236-3290.
Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps.
Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the documents and related graphics published as part of the services for any purpose All such documents and related graphics are provided “as is” without warranty of any kind Microsoft and/or its respective suppliers hereby disclaim all warranties and conditions with regard to this information, including all warranties and conditions of merchant- ability, whether express, implied or statutory, fitness for a particular purpose, title and non-infringement In no event shall Microsoft and/or its respective suppliers be liable for any special, indirect or consequential damages or any dam- ages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of information available from the services The documents and related graphics contained herein could include technical inaccuracies or typographical errors Changes are periodically added to the information herein Microsoft and/or its respective suppliers may make improve- ments and/or changes in the product(s) and/or the program(s) described herein at any time Partial screen shots may
be viewed in full within the software version specified.
Library of Congress Cataloging-in-Publication Data on file.
10 9 8 7 6 5 4 3 2 1
ISBN-10: 0-13-337933-7
ISBN-13: 978-0-13-337933-4
Trang 8To our review team
Trang 9Microsoft ® and Windows ® are registered trademarks of the Microsoft Corporation in the U.S.A and other countries This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation UNIX is a registered trademark of The Open Group.
Throughout this book, trademarks are used Rather than put a trademark symbol in every occurrence of
a trademarked name, we state that we are using the names in an editorial fashion only and to the benefit
of the trademark owner, with no intention of infringement of the trademark.
Trang 10Chapters 24–35 and Appendices D–G are PDF documents posted online at the book’s Companion Website (located at www.pearsonhighered.com/deitel/ ).
1 Introduction to Computers, the Internet
1.8.4 An International Standard; Other C# Implementations 12
1.11.1 Selling Your Apps in the Windows Phone Marketplace 18
1.13 Visual Studio Express 2012 Integrated Development Environment 19
Contents
Trang 111.14 PainterTest-Drive in Visual Studio Express 2012 for Windows Desktop 191.15 PainterTest-Drive in Visual Studio Express 2012 for Windows 8 23
2 Dive Into® Visual Studio Express 2012
2.6 Using Visual App Development to Create a Simple App that Displays
3.5 Formatting Text withConsole.WriteandConsole.WriteLine 80
4.7 Software Engineering with Properties andsetandgetAccessors 121
Trang 127.3 staticMethods,staticVariables and ClassMath 234
7.9.2 Random-Number Repeatability for Testing and Debugging 2507.10 Case Study: A Game of Chance; Introducing Enumerations 250
Trang 138.4.3 Calculating a Value to Store in Each Array Element 291
8.4.5 Using Bar Charts to Display Array Data Graphically 293
8.4.7 Using Arrays to Analyze Survey Results; Introduction to
9 Introduction to LINQ and the List Collection 351
10.4 Referring to the Current Object’s Members with thethisReference 377
Trang 14Contents xi
11.4.2 Creating aBasePlusCommissionEmployeeClass without
11.4.3 Creating aCommissionEmployee–BasePlusCommissionEmployee
11.4.4 CommissionEmployee–BasePlusCommissionEmployeeInheritance
11.4.5 CommissionEmployee–BasePlusCommissionEmployeeInheritance
12.5.2 Creating Concrete Derived ClassSalariedEmployee 453
12.5.4 Creating Concrete Derived ClassCommissionEmployee 45712.5.5 Creating Indirect Concrete Derived Class
12.5.6 Polymorphic Processing, Operatorisand Downcasting 460
Trang 1512.5.7 Summary of the Allowed Assignments Between Base-Class
12.7.4 Modifying ClassEmployeeto Implement InterfaceIPayable 47112.7.5 Modifying ClassSalariedEmployeefor Use withIPayable 47312.7.6 Using InterfaceIPayableto ProcessInvoices andEmployees
13.3 Example: HandlingDivideByZeroExceptions andFormatExceptions 491
14 Graphical User Interfaces with
Trang 16Contents xiii
15 Graphical User Interfaces with
Trang 1716.15 (Online) Introduction to Regular Expressions 662
17.9 Creating a Sequential-Access File Using Object Serialization 702
Trang 1822.5.1 Creating the ADO.NET Entity Data Model Class Library 85822.5.2 Creating a Windows Forms Project and Configuring It to
22.5.3 Data Bindings Between Controls and the Entity Data Model 864
Trang 1923.2 Web Basics 899
23.7.3 Options.aspx: Selecting a Programming Language 92823.7.4 Recommendations.aspx: Displaying Recommendations
23.8.1 Building a Web Form that Displays Data from a Database 93523.8.2 Modifying the Code-Behind File for the Guestbook App 940
23.10 Online Case Study: Password-Protected Books Database App 942
Chapters 24–35 and Appendices D–G are PDF documents posted online at the book’s Companion Website (located at www.pearsonhighered.com/deitel/ ).
Trang 20Contents xvii
Look
Computing App
with the UML
Trang 22Welcome to the Visual C#®2012 computer programming language and the world of crosoft®Windows®and Internet and web programming with Microsoft’s NET platform.Please read the book’s back cover and inside back cover—these concisely capture thebook’s essence In this Preface we provide more details.
Mi-This book is appropriate for introductory course sequences based on the curriculumrecommendations of two key professional organizations—the ACM and the IEEE Theexamples are accessible to computer science, information technology, software engineeringand business students in novice-level and intermediate-level C# courses The book can also
be used by professional programmers
At the heart of the book is the Deitel signature live-code approach—rather than using
code snippets, we present concepts in the context of complete working programs followed
by sample executions Read the Before You Begin section after this Preface for instructions
on setting up your computer to run the hundreds of code examples The source code is able atwww.deitel.com/books/vcsharp2012htpandwww.pearsonhighered.com/deitel
avail-Use the source code we provide to compile and run each program as you study it—this will
help you master Visual C# and related Microsoft technologies faster and at a deeper level
We believe that this book and its supplements for students and instructors will giveyou an informative, engaging, challenging and entertaining introduction to Visual C# Ifyou have questions, we’re easy to reach atdeitel@deitel.com—we’ll respond promptly.For book updates, visitwww.deitel.com/books/vcsharp2012htp, join our social mediacommunities on Facebook (www.deitel.com/DeitelFan), Twitter (@deitel), Google+(gplus.to/deitel) and LinkedIn (bit.ly/DeitelLinkedIn), and subscribe to the
Deitel® Buzz Online newsletter (www.deitel.com/newsletter/subscribe.html)
Visual C#® 2012, the Visual Studio® 2012 IDE, NET 4.5,
Windows® 7 and Windows® 8
The new Visual C# 2012 and its associated technologies motivated us to write Visual C#
2012 How to Program, 5/e These are some of the key features of this new edition:
• Use with Windows 7, Windows 8 or both The book is designed so that you can
continue to use Windows 7 now and begin to evolve to Windows 8, if you like,
or you can move right to Windows 8 All of the code examples in Chapters 1–24
and 28–35 were tested on both Windows 7 and Windows 8 The code examples
for the Windows-8-specific chapters—Chapter 25 (Windows 8 UI and XAML),Chapter 26 (Windows 8 Graphics and Multimedia) and Chapter 27 (Building a
Windows Phone 8 App)—were tested only on Windows 8.
• C# and Visual C# The C# language has been standardized internationally by
ECMA and ISO (the standards document is available free of charge atbit.ly/ ECMA334) Visual C# 2012 is Microsoft’s implementation of this standard
Preface
Trang 23• Modular multi-GUI treatment with Windows Forms, Windows 8 UI and WPF.
The printed book features Windows Forms GUI; optional online chapters tain treatments of Windows 8 UI (user interface) and WPF GUI Windows 8 UI
con-apps are called Windows Store con-apps In Chapter 25, you’ll learn how to create and
test Windows Store apps and upload them to Microsoft’s Windows Store
• Modular treatment of graphics and multimedia with Windows 8 and WPF The
book features optional online chapters on both Windows 8 Graphics and media (Chapter 26) and WPF Graphics and Multimedia (Chapter 33)
Multi-• Database with LINQ to Entities In the previous edition of this book, we
dis-cussed LINQ (Language Integrated Query) to SQL (Microsoft’s SQL Server tabase system) Microsoft stopped further development on LINQ to SQL in
da-2008 in favor of the newer and more robust LINQ to Entities and theADO.NET Entity Framework, which we’ve switched to in this edition, keepingthe discussion friendly for novices
• SQL Server database We use Microsoft’s free SQL Server Express 2012 (which
installs with the free Visual Studio Express 2012 for Windows Desktop) to ent the fundamentals of database programming Chapters 22–23 and 29–30 usedatabase and LINQ capabilities to build an address-book desktop app, a web-based guestbook app, a bookstore app and an airline reservation system app
pres-• ASP.NET 4.5 Microsoft’s NET server-side technology, ASP.NET, enables you
to create robust, scalable web-based apps In Chapter 23, you’ll build severalapps, including a web-based guestbook that uses ASP.NET and the ADO NETEntity Framework to store data in a database and display data in a web page Thechapter also discusses the IIS Express web server for testing your web apps onyour local computer
• Building a Windows Phone 8 App Windows Phone 8 is Microsoft’s latest
oper-ating system for smartphones It features multi-touch support for touchpads andtouchscreen devices, enhanced security features and more In Chapter 27, you’llbuild a complete working Windows Phone 8 app and test it on the WindowsPhone simulator; we’ll discuss how to upload apps to the Windows Phone Store
• Building a Windows Azure™ Cloud Computing App Windows Azure is a cloud
computing platform that allows you to develop, manage and distribute your apps
in the cloud Chapter 31 shows you how to build a Windows Azure app that canstore data in the cloud
• Asynchronous programming with async and await Asynchronous programming
is simplified in Visual C# 2012 with the newasyncandawaitcapabilities Weintroduce asynchronous programming withasyncandawaitin Chapter 28
Object-Oriented Programming
• Early-objects approach The book introduces the basic concepts and terminology
of object technology in Chapter 1 In Chapter 2, Dive Into Visual Studio 2012
Ex-press for Windows Desktop, you’ll visually manipulate objects, such as labels and images In Chapter 3, Introduction to C# Apps, you’ll write Visual C# program code
Trang 24Complete Code Examples xxi
that manipulates preexisting objects You’ll develop your first customized classesand objects in Chapter 4 Presenting objects and classes early gets you “thinkingabout objects” immediately and mastering these concepts more thoroughly
• Rich coverage of programming fundamentals Chapters 5 and 6 present a friendly
treatment of control statements and problem solving
• A clear, example-driven presentation of classes, objects, inheritance, phism and interfaces.
polymor-• Optional case study: Using the UML to develop an object-oriented design and sual C# implementation of an Automated Teller Machine (ATM) The UML™
Vi-(Unified Modeling Language™) is the industry-standard graphical language formodeling object-oriented systems We introduce the UML in the early chapters
Online Chapters 34 and 35 include an optional case study on object-oriented
de-sign using the UML We dede-sign and implement the software for a simple
automat-ed teller machine We analyze a typical requirements document that specifies the system to be built We determine the classes needed to implement that system, the
attributes the classes need to have, the behaviors the classes need to exhibit and we
specify how the classes must interact with one another to meet the system
require-ments From the design we produce a complete working Visual C# tion Students often report a “light bulb moment”—the case study helps them “tie
implementa-it all together” and truly understand object orientation
• Three programming paradigms We discuss structured programming,
object-orient-ed programming and generic programming.
Complete Code Examples
We include a broad range of example programs selected from computer science, business,simulation, game playing, graphics, multimedia and many other areas (Fig 1)
Examples
Accountclass
Address book case study
Airline reservation web-service
Animating the width and
Common WPF controlsCompound interest calcula-tions
Counter-controlled repetitionCraps dice game simulationCreating and using a text fileCreating custom windows andusing timers
Credit-inquiry programData binding
DateclassDateTimePickercontrolDefining gradients in XAMLDice rolling
DirectoryclassDocument navigation usingXNode
Drawing basic shapesDrawing polylines and poly-gons
EmployeeclassFileclass
Fig 1 | A small sample of the book’s hundreds of examples (Part 1 of 2.)
Trang 25Interesting, Entertaining and Challenging Exercises
• Extensive self-review exercises and answers are included for self-study.
• Each chapter concludes with a substantial set of exercises, which generally cludes simple recall of important terminology and concepts, identifying the errors
in-in code samples, writin-ing in-individual program statements, writin-ing small portions
of Visual C# classes, writing complete programs and implementing major ects Figure 2 lists a small sampling of the book’s hundreds of exercises, including
proj-selections from our Making a Difference exercises set, which encourage you to use
computers and the Internet to research and solve significant social problems—we
hope you’ll approach these exercises with your own values, politics and beliefs.
Formatting fonts
Generic classStack
Generic classList
Sequential searchSorting an arrayStack unwinding
StringBuilderclassTabControlText-to-speech and speech-to-text
TimeclassToolbarsTreeViewcontrol
TV GUI showing GUIcustomizationPoll analysisPolymorphism demonstrationQuerying a database withLINQ to EntitiesQueueclass
RadioButtoncontrol
Exercises
Airline Reservations System
All Possible Three-Letter Words
from a Five-Letter Word
BaseballDatabase App
Binary Tree Traversals
Blackjack
Body Mass Index Calculator
Bucket Sort
Building Your Own Computer
Calendar and Appointments
Carbon Footprint Calculator
Card Shuffling and DealingCar-Pool Savings CalculatorCoin Tossing
Complex NumbersComputer-Assisted InstructionComputerization of HealthRecords
Cooking with HealthierIngredients
Credit Limit CalculatorDice Rolling
EcofontEight QueensEmployeeClassEnforcing Privacy withCryptographyEnhanced PainterFactorialsFuzzy Dice Order FormGame of CrapsGas MileageGeneric Method Overloading
Fig 2 | A sampling of the book’s exercises (Part 1 of 2.)
Examples
Fig 1 | A small sample of the book’s hundreds of examples (Part 2 of 2.)
Trang 26Illustrations and Figures xxiii
Illustrations and Figures
Abundant tables, line drawings, UML diagrams, programs and program outputs are cluded A sampling of these is shown in Figs 3 and 4
in-Guess the Number Game
Polymorphic Banking Program
UsingAccountHierarchy
Pythagorean Triples
QuicksortQuiz AppRationalNumbersRestaurant Bill CalculatorSalary CalculatorSales CommissionsSavings-Account ClassSieve of EratosthenesTortoise and Hare SimulationSMS Language
Spam ScannerStory Writer
Student PollTarget-Heart-Rate CalculatorTax Plan Alternatives: The
“FairTax”
Telephone-Number WordGenerator
Tic-Tac-ToeTowers of HanoiTurtle GraphicsTyping TutorWeb-based Address BookWorld Population Growth
Main text tables, drawings and diagrams
Anchoring demonstration
Ajax-enabled web app
Binary tree graphical
represen-tation
Circular, doubly linked list
Circular, singly linked list
Client receiving a response
from a web server
Client requesting a response
from a web server
Creating a web service
Collection classes of the NET
Framework
Common built-in commands
from the WPF command
Increment and decrementoperators
insertAtBackoperation sented graphically
repre-insertAtFrontoperation resented graphicallyInteraction between a web-service client and a SOAPweb service
rep-Interfaces of the NET work Class LibraryKeyboard events and eventarguments
Frame-Keywords and contextualkeywords
Linked list graphicalrepresentation
LINQ to XML class hierarchy
Master/DetailappMathclass methodsMouse events and eventarguments
.NET Framework ClassLibrary namespacesNumber of comparisons forcommon Big O notationsObject methods inherited byall classes
Polymorphic interface for theEmployeehierarchy classesPrecedence of arithmetic oper-ators
removeFromBackoperationrepresented graphicallyremoveFromFrontoperationrepresented graphicallyRules of forming structuredapps
SDI and MDI forms
Fig 3 | A sampling of the book’s tables, drawings and diagrams (Part 1 of 2.)
Exercises
Fig 2 | A sampling of the book’s exercises (Part 2 of 2.)
Trang 27Other Features
• We use LINQ to query files, databases, XML and collections The introductory
LINQ to Objects chapter (Chapter 9), is intentionally simple and brief to courage instructors to begin covering LINQ technology early Later in the book,
en-we take a deeper look, using LINQ to Entities (Chapters 22–23 and 29–30) andLINQ to XML (Chapters 24, 30 and 31)
• Local type inference When you initialize a local variable in its declaration, you
can omit the variable’s type—the compiler infers it from the initializer value.
• Object initializers For new objects, you can use object initializer syntax (similar
to array initializer syntax) to assign values to the new object’spublicpropertiesandpublicinstance variables
• We emphasize the IDE’s IntelliSense feature that helps you write code faster and
with fewer errors
• Files and strings.
• Data structures chapter sequence, including searching and sorting, data tures, generics and collections.
struc-Searching and sorting
algorithms with Big O values
Tree structure for thedocumentarticle.xmlValidation app enhanced byASP.NET Ajax
XSL style-sheet elements
Object-oriented design case study drawings and diagrams
Use case diagram for the ATM system from the
user’s perspective
Class diagram with an association among classes
Class diagram showing composition relationships
Class diagram for the ATM system model
Classes with attributes
State diagram for the ATM
Activity diagram for aBalanceInquirytransaction
Activity diagram for aWithdrawaltransaction
Classes in the ATM system with attributes and
Class diagram showing composition ships of a classCar
relation-Class diagram for the ATM system modelincluding classDeposit
Activity diagram for aDeposittransactionSequence diagram that models aDepositexecuting
Fig 4 | A sampling of the object-oriented design case study drawings and diagrams
Main text tables, drawings and diagrams
Fig 3 | A sampling of the book’s tables, drawings and diagrams (Part 2 of 2.)
Trang 28Companion Website xxv
• Integrated exception handling We introduce exception handling early (Chapter 8,
Arrays; Introduction to Exception Handling) to ensure that we do not access anarray element outside the array’s bounds Chapter 10, Classes and Objects:
A Deeper Look, shows how to indicate an exception when a member function ceives an invalid argument We cover the complete details of exception handling inChapter 13, Exception Handling: A Deeper Look
re-• Visual C# XML capabilities Extensible Markup Language (XML) is pervasive in
the software-development industry, e-business and throughout the NET platform
In optional online Chapter 24, we introduce XML syntax and programmaticallymanipulate the elements of an XML document using LINQ to XML XAML is anXML vocabulary that’s used to describe graphical user interfaces, graphics and mul-timedia We discuss XAML in optional online Chapters 25–26 and 32–33
• Web app development with ASP.NET 4.5 and ASP.NET AJAX Optional online
Chapter 29 extends Chapter 23’s ASP.NET discussion with a case study onbuilding a password-protected, web-based bookstore app Also, we introduce inChapter 29 ASP.NET AJAX controls and use them to add AJAX functionality toweb apps to give them a look and feel similar to that of desktop apps
• WCF (Windows Communication Foundation) web services Web services enable
you to package app functionality in a manner that turns the web into a library of
reusable services Optional online Chapter 30 includes case studies on building an
airline reservation web service, a blackjack web service and a math question erator web service that’s called by a math tutor app
gen-• WPF (Windows Presentation Foundation) GUI, graphics and multimedia We
extend the core book’s GUI coverage in optional online Chapters 32–33 with anintroduction to Windows Presentation Foundation (WPF)—a XAML-based Mi-crosoft framework that preceded Windows 8 UI and integrates GUI, graphicsand multimedia capabilities We implement a painting app, a text editor, a colorchooser, a book-cover viewer, a television video player, various animations, andspeech synthesis and recognition apps
Companion Website
The printed book contains the core content (Chapters 1–23) for introductory course quences Several optional online chapters are available for advanced courses and profes-sionals Figure 5 lists the chapters and appendices that are available in searchable PDFformat on the book’s password-protected Companion Website at:
se-See the inside front cover of the book for an access code
www.pearsonhighered.com/deitel
Online chapters
Chapter 24, XML and LINQ to XML
Chapter 25, Windows 8 UI and XAML
Fig 5 | Online chapters and appendices in Visual C# 2012 How to Program, 5/e (Part 1 of 2.)
Trang 29The Companion Website also includes extensive VideoNotes—watch and listen as
co-au-thor Paul Deitel discusses key code examples in the core chapters of the book VideoNotesallow for self-paced instruction with easy navigation, including the ability to select, play,rewind, fast-forward and stop within each video
We’ve created a jump table that maps each VideoNote to the corresponding figures
in the book (www.deitel.com/books/vcsharphtp5/jump_table.pdf) VideoNotes are
free with the purchase of a new textbook If you have a used book you can purchase access
to the VideoNotes for this book as follows:
1 Go towww.pearsonhighered.com/deitel/
2 Scroll to Visual C# 2012 How to Program, 5/e and clickCompanion Website
3 Click the Registerbutton
4 On the registration page, enter your student access code found beneath the
scratch-off panel on the inside front cover of this book Do not type the dashes
You can use lower- or uppercase The access code can be used only once This scription is valid for twelve months upon activation and is not transferable If this
sub-access code on your book has already been revealed, it may no longer be valid Ifthis is the case, click theWebsite Purchaselink and follow the instructions
5 Once your personal Login Name and Password are confirmed, you can begin
us-ing the Visual C# 2012 How to Program, 5/e Companion Website.
Chapter 26, Windows 8 Graphics and Multimedia
Chapter 27, Building a Windows Phone 8 App
Chapter 28, Introduction to Concurrency:asyncandawait
Chapter 29, Web App Development with ASP.NET: A Deeper Look
Chapter 30, Web Services
Chapter 31, Building a Windows Azure™ Cloud Computing App
Chapter 32, GUI with Windows Presentation Foundation
Chapter 33, WPF Graphics and Multimedia
Chapter 34, ATM Case Study, Part 1: Object-Oriented Design with the UML
Chapter 35, ATM Case Study, Part 2: Implementing an Object-Oriented Design
Appendix D, Number Systems
Appendix E, UML 2: Additional Diagram Types
Appendix F, Unicode®
Appendix G, Using the Visual Studio 2012 Debugger
Index (The online index includes the content from the printed book and the online content.The printed book index covers only the printed material.)
Online chapters
Fig 5 | Online chapters and appendices in Visual C# 2012 How to Program, 5/e (Part 2 of 2.)
Trang 30Book Overview and Chapter Dependencies xxvii
Book Overview and Chapter Dependencies
This section discusses the book’s modular organization to help instructors plan their syllabi
Introduction to Visual C# and Visual Studio 2012 Express
Chapter 1, Introduction to Computers, the Internet and Visual C#, introduces ing fundamentals and Microsoft’s NET platform If you do not need to cover these fun-damentals, you should still cover thePainterapp test-drive The vast majority of the book’s
comput-examples will run on Windows 7 and Windows 8 using Visual Studio Express 2012 for
Windows Desktop, which we test-drive in Section 1.14 Chapters 25–26 can be run only on
Windows 8 using Visual Studio Express 2012 for Windows 8, which we test-drive in Section 1.15 There are other versions of Visual Studio Express 2012 for web development
and Windows Phone development—we cover these in the corresponding chapters.Chapter 2, Dive Into® Visual Studio Express 2012 for Windows Desktop, showshow to develop a simple GUI app that displays text and an image We’ll look at VisualStudio Express 2012 for Windows 8 in more depth in Chapter 25
Introduction to Visual C# Fundamentals and Object-Oriented Programming
The chapters in this module of the book:
• Chapter 3, Introduction to C# Apps
• Chapter 4, Introduction to Classes, Objects, Methods and strings
• Chapter 5, Control Statements: Part 1
• Chapter 6, Control Statements: Part 2
• Chapter 7, Methods: A Deeper Look
• Chapter 8, Arrays; Introduction to Exception Handling
present C# programming fundamentals (data types, operators, control statements, ods and arrays) and introduce object-oriented programming These chapters should becovered in order Chapter 8 introduces exception handling with an example that demon-strates accessing an element outside an array’s bounds
meth-Object-Oriented Programming: A Deeper Look
The chapters in this module of the book:
• Chapter 9, Introduction to LINQ and theListCollection
• Chapter 10, Classes and Objects: A Deeper Look
• Chapter 11, Object-Oriented Programming: Inheritance
• Chapter 12, OOP: Polymorphism, Interfaces and Operator Overloading
• Chapter 13, Exception Handling: A Deeper Look
• Chapter 34, ATM Case Study, Part 1: Object-Oriented Design with the UML
• Chapter 35, ATM Case Study, Part 2: Implementing an Object-Oriented Designprovide a deeper look at object-oriented programming, including classes, objects, inheri-tance, polymorphism, interfaces and exception handling Chapter 9, Introduction to LINQand theListCollection, introduces Microsoft’s Language Integrated Query (LINQ) tech-nology, which provides a uniform syntax for manipulating data from various data sources,
Trang 31such as arrays, collections and, as you’ll see in later chapters, XML and databases This ter can be deferred, but it’s required for one example in Chapter 17 (Fig 17.6) and many ofthe later chapters starting with Chapter 22, Databases and LINQ Online Chapters 34–35
chap-present an optional object-oriented design and implementation case study that requires the
C# and object-oriented programming concepts presented in Chapters 3–8 and 10–13
Windows Form s Graphical User Interfaces (GUIs)
There are now three GUI technologies in Windows—WindowsForms (which is a legacy
technology), Windows 8 UI (available only on Windows 8) and Windows Presentation
Foundation (WPF) We surveyed instructors teaching Visual C# and they still prefer dowsForms for their classes, so we provide a two-chapter introduction to WindowsForms:
Win-• Chapter 14, Graphical User Interfaces with Windows Forms: Part 1
• Chapter 15, Graphical User Interfaces with Windows Forms: Part 2
in the print book, then use WindowsForms GUIs in several other print and online ters Most examples in Chapters 14–15 can be presented after Chapter 4 For those whowish to present or study Microsoft’s more recent GUI, graphics and multimedia technol-ogies, we provide two-chapter online introductions to Windows 8 UI, graphics and mul-timedia (Chapters 25–26) and WPF GUI, graphics and multimedia (Chapters 32–33)
chap-Strings and Files
We introduce strings beginning in Chapter 4 and use them throughout the book.Chapter 16, Strings and Characters: A Deeper Look, investigatesstrings in more depth.Chapter 17, Files and Streams, introduces text-file processing and object-serialization forinput/output of entire objects Chapter 16 can be presented at any point after Chapter 4.Chapter 17 requires C#, object-oriented programming and WindowsForms concepts pre-sented in Chapters 3–14
Searching, Sorting and Data Structures
The chapters in this module of the book:
• Chapter 18, Searching and Sorting
• Chapter 19, Data Structures
• Chapter 20, Generics
• Chapter 21, Collections
introduce searching, sorting and data structures Most C# programmers should use
.NET’s built-in searching, sorting and collections (prepackaged data structures)
capabili-ties, which are discussed in Chapter 21 For instructors who wish to present how to plement customized searching, sorting and data structures capabilities, we provideChapters 18–20, which require the concepts presented in Chapters 3–8 and 10–13
im-Databases and an Introduction to Web App Development
Chapter 22, Databases and LINQ, introduces database app development using theADO.NET Entity Framework and LINQ to Entities The chapter’s examples require C#,object-oriented programming and WindowsForms concepts presented in Chapters 3–14.Chapter 23, Web App Development with ASP.NET, introduces web app development
Trang 32Book Overview and Chapter Dependencies xxix
The last example in this chapter requires the LINQ and database techniques presented inChapter 22
Extensible Markup Language (XML)
Chapter 24, XML and LINQ to XML, introduces XML, which is used in several later ters The first few sections of this chapter are required to understand the XAML markupthat’s used to build Windows 8 GUI, graphics and multimedia apps (Chapters 25–26),Windows Phone 8 apps (Chapter 27) and WPF GUI, graphics and multimedia apps(Chapters 32–33) The remainder of the chapter discusses LINQ to XML, which allows you
chap-to manipulate XML using LINQ syntax These capabilities are used in Chapters 30 and 31
Windows 8 UI, Graphics and Multimedia; Windows Phone
The chapters in this module of the book:
• Chapter 25, Windows 8 UI and XAML
• Chapter 26, Windows 8 Graphics and Multimedia
• Chapter 27, Building a Windows Phone 8 App
present Windows 8 UI, graphics and multimedia, and Windows Phone 8 app ment These chapters can be used only on computers running Windows 8 and depend onevent-handling concepts that are presented in Chapter 14, and the introduction to XML
develop-at the beginning of Chapter 24 (see Section 24.1 for details) Developing a WindowsPhone 8 app is similar to developing a Windows 8 UI app
Asynchronous Programming
Chapter 28, Asynchronous Programming with async andawait, demonstrates NET’sand Visual C#’s new simplified asynchronous programming capabilities These are com-monly used in Web app and Web service development (among many other uses)
Web App Development and Web Services
The chapters in this module of the book:
• Chapter 29, Web App Development with ASP.NET: A Deeper Look
• Chapter 30, Web Services
• Chapter 31, Building a Windows Azure™ Cloud Computing App
continue our discussion of Web app development from Chapter 23 and introduce web vices, including a case study on cloud computing with Windows Azure Chapters 30 and
ser-31 depend on the LINQ to XML discussion in Chapter 24
Windows Presentation Foundation (WPF) GUI, Graphics and Multimedia
The chapters in this module of the book
• Chapter 32, GUI with Windows Presentation Foundation
• Chapter 33, WPF Graphics and Multimedia
discuss Windows Presentation Foundation GUI, graphics and multimedia These ters can be used on computers running Windows 7 or Windows 8 and depend on event-handling concepts that are presented in Chapter 14 and the introduction to XML at thebeginning of Chapter 24
Trang 33chap-Teaching Approach
Visual C# 2012 How to Program, 5/e contains a rich collection of examples We
concen-trate on building good software and stress program clarity
Live-Code Approach The book is loaded with “live-code” examples Most new concepts
are presented in the context of complete working Visual C# apps, followed by one or moreexecutions showing program inputs and outputs In the few cases where we show a codesnippet, to ensure correctness we first tested it in a complete working program then copiedthe code from the program and pasted it into the book
Syntax Shading.For readability, we syntax shade the code, similar to the way most grated-development environments and code editors syntax color the code Our syntax-shading conventions are:
inte-Code Highlighting.We place gray rectangles around each program’s key code segments
Using Fonts for Emphasis We place the key terms and the index’s page reference for each
defining occurrence in bold text for easy reference We show on-screen components in the
bold Helveticafont (for example, theFilemenu) and Visual C# program text in theLucidafont (for example,int count = 5) We use italics for emphasis.
Objectives The chapter objectives preview the topics covered in the chapter.
Programming Tips.We include programming tips to help you focus on important pects of program development These tips and practices represent the best we’ve gleanedfrom a combined seven decades of programming and teaching experience
as-comments appear like this
keywords appear like this
constants and literal values appear like this
all other code appears in black
Good Programming Practice
The Good Programming Practices call attention to techniques that will help you duce programs that are clearer, more understandable and more maintainable.
pro-Common Programming Error
Pointing out these Common Programming Errors reduces the likelihood that you’ll make them.
Error-Prevention Tip
These tips contain suggestions for exposing and removing bugs from your programs; many
of the tips describe aspects of Visual C# that prevent bugs from getting into programs.
Trang 34Obtaining the Software Used in Visual C# How to Program, 5/e xxxi
Summary Bullets We present a detailed bullet-list summary of each chapter.
Terminology We include a list of the important terms defined in each chapter.
Index We’ve included an extensive index for reference Defining occurrences of key terms
in the index are highlighted with a bold page number.
Obtaining the Software Used in Visual C# How to Program, 5/e
We wrote the code examples in Visual C# 2012 How to Program, 5/e using Microsoft’s free
Visual Studio Express 2012 products, including:
• Visual Studio Express 2012 for Windows Desktop (Chapters 1–24, 28 and 32–35), which includes Visual C# and other Microsoft development tools This runs
on Windows 7 and 8.
• Visual Studio Express 2012 for Web (Chapters 23 and 29–31)
• Visual Studio Express 2012 for Windows 8 (Chapters 25–26)
• Visual Studio Express 2012 for Windows Phone (Chapter 27)
Each of these is available for download at
Instructor Supplements
The following supplements are available to qualified instructors only through Pearson
Education’s Instructor Resource Center (www.pearsonhighered.com/irc):
• Solutions Manual contains solutions to most of the end-of-chapter exercises We’ve added many Making a Difference exercises, most with solutions Please do not write
to us requesting access to the Pearson Instructor’s Resource Center Access is stricted to college instructors teaching from the book Instructors may obtain ac- cess only through their Pearson representatives If you’re not a registered faculty
re-member, contact your Pearson representative or visitwww.pearsonhighered.com/ educator/replocator/ Exercise Solutions are not provided for “project” exercis-
es Check out our Programming Projects Resource Center for lots of additional ercise and project possibilities:
ex-• Test Item File of multiple-choice questions (approximately two per book section)
• Customizable PowerPoint ® slides containing all the code and figures in the text,
plus bulleted items that summarize the key points in the text
Software Engineering Observation
The Software Engineering Observations highlight architectural and design issues that affect the construction of software systems, especially large-scale systems.
Trang 35Microsoft DreamSpark™
Professional Developer and Designer Tools for Students
Microsoft provides many of its professional developer tools to students for free via a gram called DreamSpark (www.dreamspark.com) See the website for details on verifyingyour student status so you take advantage of this program
pro-Acknowledgments
We’d like to thank Abbey Deitel and Barbara Deitel of Deitel & Associates, Inc for longhours devoted to this project Abbey co-authored this Preface and Chapter 1 and she andBarbara painstakingly researched the new capabilities of Visual C# 2012, NET 4.5, Win-dows 8, Windows Phone 8, Windows Azure and other key topics
We’re fortunate to have worked with the dedicated team of publishing professionals
at Pearson Higher Education We appreciate the guidance, wisdom and energy of TracyJohnson, Executive Editor, Computer Science Carole Snyder did an extraordinary jobrecruiting the book’s reviewers and managing the review process Bob Engelhardt did awonderful job bringing the book to publication
Reviewers
We wish to acknowledge the efforts of our reviewers The book was scrutinized by demics teaching C# courses and industry experts They provided countless suggestions forimproving the presentation Any remaining flaws in the book are our own
aca-Fifth Edition Reviewers: Shay Friedman (Microsoft Visual C# MVP), Octavio
Her-nandez (Microsoft Certified Solutions Developer), Stephen Hustedde (South MountainCollege), José Antonio González Seco (Parliament of Andalusia, Spain) and Shawn Weis-feld (Microsoft MVP and President and Founder of UserGroup.tv)
Other recent edition reviewers: Huanhui Hu (Microsoft Corporation), Narges Kasiri
(Oklahoma State University), Charles Liu (University of Texas at San Antonio), Dr.Hamid R Nemati (The University of North Carolina at Greensboro), Jeffrey P Scott(Blackhawk Technical College), Douglas B Bock (MCSD.NET, Southern Illinois Uni-versity Edwardsville), Dan Crevier (Microsoft), Amit K Ghosh (University of Texas at ElPaso), Marcelo Guerra Hahn (Microsoft), Kim Hamilton (Software Design Engineer at
Microsoft and co-author of Learning UML 2.0), James Edward Keysor (Florida Institute
of Technology), Helena Kotas (Microsoft), Chris Lovett (Software Architect at soft), Bashar Lulu (INETA Country Leader, Arabian Gulf), John McIlhinney (SpatialIntelligence; Microsoft MVP 2008 Visual Developer, Visual Basic), Ged Mead (MicrosoftVisual Basic MVP, DevCity.net), Anand Mukundan (Architect, Polaris Software LabLtd.), Timothy Ng (Microsoft), Akira Onishi (Microsoft), Joe Stagner (Senior ProgramManager, Developer Tools & Platforms), Erick Thompson (Microsoft), Jesús UbaldoQuevedo-Torrero (University of Wisconsin–Parkside, Department of Computer Science)and Zijiang Yang (Western Michigan University)
Micro-As you read the book, we’d sincerely appreciate your comments, criticisms and gestions for improving the text Please address all correspondence to:
sug-deitel@deitel.com
Trang 36About the Authors xxxiii
We’ll respond promptly We really enjoyed writing this book—we hope you enjoy readingit!
Paul Deitel
Harvey Deitel
About the Authors
Paul Deitel, CEO and Chief Technical Officer of Deitel & Associates, Inc., is a graduate
of MIT, where he studied Information Technology Through Deitel & Associates, Inc.,
he has delivered hundreds of programming courses to industry clients, including Cisco,IBM, Siemens, Sun Microsystems, Dell, Fidelity, NASA at the Kennedy Space Center, theNational Severe Storm Laboratory, White Sands Missile Range, Rogue Wave Software,Boeing, SunGard Higher Education, Nortel Networks, Puma, iRobot, Invensys and manymore He and his co-author, Dr Harvey M Deitel, are the world’s best-selling program-ming-language textbook/professional book/video authors
Paul was named as a Microsoft®Most Valuable
Professional (MVP) for C# in 2012 According to
Microsoft, “the Microsoft MVP Award is an annual
award that recognizes exceptional technology
commu-nity leaders worldwide who actively share their high
quality, real world expertise with users and
Micro-soft.”
Dr Harvey Deitel, Chairman and Chief Strategy Officer of Deitel & Associates, Inc.,
has 50 years of experience in the computer field Dr Deitel earned B.S and M.S degrees
in Electrical Engineering from MIT and a Ph.D in Mathematics from Boston University
He has extensive college teaching experience, including earning tenure and serving as theChairman of the Computer Science Department at Boston College before foundingDeitel & Associates, Inc., in 1991 with his son, Paul Deitel The Deitels’ publications haveearned international recognition, with translations published in Chinese, Korean, Japa-nese, German, Russian, Spanish, French, Polish, Italian, Portuguese, Greek, Urdu andTurkish Dr Deitel has delivered hundreds of programming courses to corporate, aca-demic, government and military clients
Deitel® Dive-Into® Series Programming Languages Training
Deitel & Associates, Inc., founded by Paul Deitel and Harvey Deitel, is an internationallyrecognized authoring and corporate training organization, specializing in computer pro-gramming languages, object technology, mobile app development and Internet and websoftware technology The company’s training clients include many of the world’s largestcompanies, government agencies, branches of the military, and academic institutions Thecompany offers instructor-led training courses delivered at client sites worldwide on majorprogramming languages and platforms, including Visual C#®, Visual Basic®, VisualC++®, C++, C, Java™, XML®, Python®, object technology, Internet and web program-ming, Android app development, Objective-C and iPhone app development and a grow-ing list of additional programming and software development courses
2012 C# MVP
Trang 37Through its 37-year publishing partnership with Prentice Hall/Pearson, Deitel &Associates, Inc., publishes leading-edge programming college textbooks, professional
books and LiveLessons video courses Deitel & Associates, Inc and the authors can be
reached at:
To learn more about Deitel’s Dive-Into ® Series Corporate Training curriculum, visit:
To request a proposal for worldwide on-site, instructor-led training at your organization,e-maildeitel@deitel.com
Individuals wishing to purchase Deitel books and LiveLessons video training can do so
throughwww.deitel.com Bulk orders by corporations, the government, the military andacademic institutions should be placed directly with Pearson For more information, visit
deitel@deitel.com
www.deitel.com/training
www.informit.com/store/sales.aspx
Trang 38This section contains information you should review before using this book and tions to ensure that your computer is set up properly for use with this book.
instruc-Font and Naming Conventions
We use fonts to distinguish between features, such as menu names, menu items, and otherelements that appear in the program-development environment Our convention is to em-phasize IDE features in a sans-serif boldHelveticafont (for example,Propertieswindow)and to emphasize program text in a sans-serifLucidafont (for example,bool x = true)
Software
This textbook uses the following software:
• Microsoft Visual Studio Express 2012 for Windows Desktop
• Microsoft Visual Studio Express 2012 for Web (Chapters 23 and 29–31)
• Microsoft Visual Studio Express 2012 for Windows 8 (Chapters 25–26)
• Microsoft Visual Studio Express 2012 for Windows Phone (Chapter 27)
Each is available free for download atwww.microsoft.com/express The Express Editionsare fully functional, and there’s no time limit for using the software
Hardware and Software Requirements for the Visual Studio 2012 Express Editions
To install and run the Visual Studio 2012 Express Editions, ensure that your system meetsthe minimum requirements specified at:
Microsoft Visual Studio Express 2012 for Windows 8 works only on Windows 8.
Viewing File Extensions
Several screenshots in Visual C# 2012 How to Program, 5/e display file names with file-name
extensions (e.g.,.txt,.csor.png) Your system’s settings may need to be adjusted to displayfile-name extensions Follow these steps to configure your Windows 7 computer:
1 In the Startmenu, selectAll Programs, thenAccessories, thenWindows Explorer
2 Press Alt to display the menu bar, then selectFolder Options…fromWindows plorer’sToolsmenu
Ex-3 In the dialog that appears, select the Viewtab
4 In the Advanced settings:pane, uncheck the box to the left of the textHide tensions for known file types [Note: If this item is already unchecked, no action
ex-needs to be taken.]
5 Click OK to apply the setting and close the dialog.
www.microsoft.com/visualstudio/eng/products/compatibility
Before You Begin
Trang 39Follow these steps to configure your Windows 8 computer:
1 On the Startscreen, click theDesktoptile to switch to the desktop
2 On the task bar, click the File Explorericon to open theFile Explorer
3 Click the View tab, then ensure that the File name extensions checkbox ischecked
Obtaining the Code Examples
The examples for Visual C# 2012 How to Program, 5/e are available for download at
If you’re not already registered at our website, go towww.deitel.comand click theRegister
link below our logo in the upper-left corner of the page Fill in your information There’s
no charge to register, and we do not share your information with anyone We send you onlyaccount-management e-mails unless you register separately for our free e-mail newsletter atwww.deitel.com/newsletter/subscribe.html You must enter a valid e-mail address After
registering, you’ll receive a confirmation e-mail with your verification code Click the link
in the confirmation email to go towww.deitel.comand sign in
Next, go towww.deitel.com/books/vcsharp2012htp/ Click theExamples link todownload the ZIP archive file to your computer Write down the location where you savethe file—most browsers will save the file into yourDownloadsfolder
Throughout the book, steps that require you to access our example code on your puter assume that you’ve extracted the examples from the ZIP file and placed them atC:\Examples You can extract them anywhere you like, but if you choose a different loca-tion, you’ll need to update our steps accordingly You can extract the ZIP archive file’scontents using tools such as WinZip (www.winzip.com), 7-zip (www.7-zip.org) or thebuilt-in capabilities ofWindows Exploreron Window 7 orFile Exploreron Windows 8
com-Visual Studio Theme
Visual Studio 2012 has aDarktheme (the default) and aLighttheme The screen capturesshown in this book use theLighttheme, which is more readable in print If you’d like toswitch to theLighttheme, in theTOOLSmenu, selectOptions…to display theOptionsdi-alog In the left column, selectEnvironment, then selectLightunderColor theme Keep the
Optionsdialog open for the next step
Displaying Line Numbers and Configuring Tabs
Next, you’ll change the settings so that your code matches that of this book To have theIDE display line numbers, expand theText Editornode in the left pane then selectAll Lan- guages On the right, check theLine numberscheckbox Next, expand the C# node in theleft pane and selectTabs Make sure that the optionInsert spacesis selected Enter3forboth theTab sizeandIndent sizefields Any new code you add will now use three spacesfor each level of indentation ClickOKto save your settings
Miscellaneous Notes
• Some people like to change the workspace layout in the development tools Youcan return the tools to their default layouts by selectingWindow > Reset Window Layout
www.deitel.com/books/vcsharp2012htp/
Trang 40Before You Begin xxxvii
• Many of the menu items we use in the book have corresponding icons shownwith each menu item in the menus Many of the icons also appear on one of thetoolbars at the top of the development environment As you become familiar withthese icons, you can use the toolbars to help speed up your development time.Similarly, many of the menu items have keyboard shortcuts (also shown witheach menu item in the menus) for accessing commands quickly
You are now ready to begin your Visual C# studies with Visual C# 2012 How to
Pro-gram, 5/e We hope you enjoy the book!