Deitel® Series Page How 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
Tutorial Approach Simply Visual Basic® 2010, 4/E: An App-Driven
Tutorial Approach
CourseSmart Web Books www.deitel.com/books/CourseSmart/
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-Driven Approach, 4/E
Visual Basic® 2012 How to Program Visual Basic® 2010 How to Program Visual C#® 2012 How to Program, 5/E Visual C#® 2010 How to Program, 4/E
Deitel® Developer Series C++ for Programmers, 2/E Android for Programmers: An App-Driven
Approach C# 2010 for Programmers, 3/E Dive Into® iOS 6: An App-Driven Approach iOS 6 for Programmers: An App-Driven Approach Java™ for Programmers, 2/E JavaScript for Programmers
LiveLessons Video Learning Products www.deitel.com/books/LiveLessons/
Android® App Development Fundamentals C++ Fundamentals C# Fundamentals iOS 6 App Development Fundamentals Java™ Fundamentals JavaScript Fundamentals Visual 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:
www.deitel.com/newsletter/subscribe.html
and join the Deitel communities on Twitter®
@deitel
Facebook®
facebook.com/DeitelFan
and Google+ gplus.to/deitel
To communicate with the authors, send e-mail to: deitel@deitel.com
For information on government and corporate Dive-Into® Series on-site seminars offered by Deitel & Associates, Inc. worldwide, visit:
www.deitel.com/training/
or write to deitel@deitel.com
For continuing updates on Prentice Hall/Deitel publications visit: www.deitel.com www.pearsonhighered.com/deitel/
Visit the Deitel Resource Centers that will help you master programming languages, software develop- ment, Android and iPhone/iPad app development, and Internet- and web-related topics:
www.deitel.com/ResourceCenters.html
Paul Deitel Deitel & Associates, Inc.
Harvey Deitel Deitel & Associates, Inc.
Vice President and Editorial Director: Marcia J. Horton Executive Editor: Tracy Johnson Associate 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. Manufac- 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 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
To our review team
Shay Friedman Octavio Hernandez Stephen Hustedde José Antonio González Seco Shawn Weisfeld
We are grateful for your guidance and expertise.
Paul and Harvey Deitel
Trademarks DEITEL, the double-thumbs-up bug and DIVE INTO are registered trademarks of Deitel and Associates, Inc.
Microsoft® 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.
Chapters 24–35 and Appendices D–G are PDF documents posted online at the book’s Companion Website (located at www.pearsonhighered.com/deitel/).
Preface xix
Before You Begin xxxv
1 Introduction to Computers, the Internet and Visual C# 1
1.1 Introduction 2 1.2 Hardware and Moore’s Law 2 1.3 Data Hierarchy 3 1.4 Computer Organization 6 1.5 Machine Languages, Assembly Languages and High-Level Languages 7 1.6 Object Technology 8 1.7 Internet and World Wide Web 10 1.8 C# 12
1.8.1 Object-Oriented Programming 12 1.8.2 Event-Driven Programming 12 1.8.3 Visual Programming 12 1.8.4 An International Standard; Other C# Implementations 12 1.8.5 Internet and Web Programming 13 1.8.6 Introducing async/await 13 1.8.7 Other Key Contemporary Programming Languages 13
1.9 Microsoft’s .NET 14 1.9.1 .NET Framework 14 1.9.2 Common Language Runtime 15 1.9.3 Platform Independence 15 1.9.4 Language Interoperability 15
1.10 Microsoft’s Windows® Operating System 16 1.11 Windows Phone 8 for Smartphones 17
1.11.1 Selling Your Apps in the Windows Phone Marketplace 18 1.11.2 Free vs. Paid Apps 18 1.11.3 Testing Your Windows Phone Apps 18
1.12 Windows Azure™ and Cloud Computing 19 1.13 Visual Studio Express 2012 Integrated Development Environment 19
Contents
viii Contents
1.14 Painter Test-Drive in Visual Studio Express 2012 for Windows Desktop 19 1.15 Painter Test-Drive in Visual Studio Express 2012 for Windows 8 23
2 Dive Into® Visual Studio Express 2012 for Windows Desktop 33
2.1 Introduction 34 2.2 Overview of the Visual Studio Express 2012 IDE 34 2.3 Menu Bar and Toolbar 39 2.4 Navigating the Visual Studio IDE 41
2.4.1 Solution Explorer 43 2.4.2 Toolbox 44 2.4.3 Properties Window 44
2.5 Using Help 46 2.6 Using Visual App Development to Create a Simple App that Displays
Text and an Image 47 2.7 Wrap-Up 57 2.8 Web Resources 58
3 Introduction to C# Apps 65 3.1 Introduction 66 3.2 A Simple C# App: Displaying a Line of Text 66 3.3 Creating a Simple App in Visual Studio 72 3.4 Modifying Your Simple C# App 77 3.5 Formatting Text with Console.Write and Console.WriteLine 80 3.6 Another C# App: Adding Integers 81 3.7 Memory Concepts 85 3.8 Arithmetic 86 3.9 Decision Making: Equality and Relational Operators 90 3.10 Wrap-Up 94
4 Introduction to Classes, Objects, Methods and strings 106
4.1 Introduction 107 4.2 Classes, Objects, Methods, Properties and Instance Variables 107 4.3 Declaring a Class with a Method and Instantiating an Object of a Class 108 4.4 Declaring a Method with a Parameter 113 4.5 Instance Variables and Properties 116 4.6 UML Class Diagram with a Property 121 4.7 Software Engineering with Properties and set and get Accessors 121 4.8 Auto-Implemented Properties 123 4.9 Value Types vs. Reference Types 123 4.10 Initializing Objects with Constructors 125 4.11 Floating-Point Numbers and Type decimal 128 4.12 Wrap-Up 134
Contents ix
5 Control Statements: Part 1 142 5.1 Introduction 143 5.2 Algorithms 143 5.3 Pseudocode 144 5.4 Control Structures 144 5.5 if Single-Selection Statement 146 5.6 if…else Double-Selection Statement 148 5.7 while Repetition Statement 152 5.8 Formulating Algorithms: Counter-Controlled Repetition 154 5.9 Formulating Algorithms: Sentinel-Controlled Repetition 158 5.10 Formulating Algorithms: Nested Control Statements 166 5.11 Compound Assignment Operators 171 5.12 Increment and Decrement Operators 171 5.13 Simple Types 174 5.14 Wrap-Up 175
6 Control Statements: Part 2 189 6.1 Introduction 190 6.2 Essentials of Counter-Controlled Repetition 190 6.3 for Repetition Statement 191 6.4 Examples Using the for Statement 195 6.5 do…while Repetition Statement 199 6.6 switch Multiple-Selection Statement 201 6.7 break and continue Statements 209 6.8 Logical Operators 211 6.9 Structured-Programming Summary 216 6.10 Wrap-Up 221
7 Methods: A Deeper Look 231 7.1 Introduction 232 7.2 Packaging Code in C# 232 7.3 static Methods, static Variables and Class Math 234 7.4 Declaring Methods with Multiple Parameters 236 7.5 Notes on Declaring and Using Methods 240 7.6 Method-Call Stack and Activation Records 241 7.7 Argument Promotion and Casting 242 7.8 The .NET Framework Class Library 243 7.9 Case Study: Random-Number Generation 245
7.9.1 Scaling and Shifting Random Numbers 249 7.9.2 Random-Number Repeatability for Testing and Debugging 250
7.10 Case Study: A Game of Chance; Introducing Enumerations 250 7.11 Scope of Declarations 255 7.12 Method Overloading 258 7.13 Optional Parameters 260
x Contents
7.14 Named Parameters 262 7.15 Recursion 263 7.16 Passing Arguments: Pass-by-Value vs. Pass-by-Reference 266 7.17 Wrap-Up 269
8 Arrays; Introduction to Exception Handling 285 8.1 Introduction 286 8.2 Arrays 286 8.3 Declaring and Creating Arrays 288 8.4 Examples Using Arrays 289
8.4.1 Creating and Initializing an Array 289 8.4.2 Using an Array Initializer 290 8.4.3 Calculating a Value to Store in Each Array Element 291 8.4.4 Summing the Elements of an Array 292 8.4.5 Using Bar Charts to Display Array Data Graphically 293 8.4.6 Using the Elements of an Array as Counters 295 8.4.7 Using Arrays to Analyze Survey Results; Introduction to
Exception Handling 296 8.5 Case Study: Card Shuffling and Dealing Simulation 299 8.6 foreach Statement 303 8.7 Passing Arrays and Array Elements to Methods 305 8.8 Passing Arrays by Value and by Reference 307 8.9 Case Study: GradeBook Using an Array to Store Grades 311 8.10 Multidimensional Arrays 316 8.11 Case Study: GradeBook Using a Rectangular Array 321 8.12 Variable-Length Argument Lists 327 8.13 Using Command-Line Arguments 329 8.14 Wrap-Up 331
9 Introduction to LINQ and the List Collection 351 9.1 Introduction 352 9.2 Querying an Array of int Values Using LINQ 353 9.3 Querying an Array of Employee Objects Using LINQ 357 9.4 Introduction to Collections 362 9.5 Querying a Generic Collection Using LINQ 365 9.6 Wrap-Up 367 9.7 Deitel LINQ Resource Center 367
10 Classes and Objects: A Deeper Look 371 10.1 Introduction 372 10.2 Time Class Case Study 372 10.3 Controlling Access to Members 376 10.4 Referring to the Current Object’s Members with the this Reference 377 10.5 Time Class Case Study: Overloaded Constructors 379
Contents xi
10.6 Default and Parameterless Constructors 385 10.7 Composition 386 10.8 Garbage Collection and Destructors 389 10.9 static Class Members 390 10.10 readonly Instance Variables 393 10.11 Data Abstraction and Encapsulation 394 10.12 Class View and Object Browser 396 10.13 Object Initializers 398 10.14 Wrap-Up 398
11 Object-Oriented Programming: Inheritance 405 11.1 Introduction 406 11.2 Base Classes and Derived Classes 407 11.3 protected Members 409 11.4 Relationship between Base Classes and Derived Classes 410
11.4.1 Creating and Using a CommissionEmployee Class 410 11.4.2 Creating a BasePlusCommissionEmployee Class without
Using Inheritance 415 11.4.3 Creating a CommissionEmployee–BasePlusCommissionEmployee
Inheritance Hierarchy 420 11.4.4 CommissionEmployee–BasePlusCommissionEmployee Inheritance
Hierarchy Using protected Instance Variables 423 11.4.5 CommissionEmployee–BasePlusCommissionEmployee Inheritance
Hierarchy Using private Instance Variables 428 11.5 Constructors in Derived Classes 433 11.6 Software Engineering with Inheritance 434 11.7 Class object 434 11.8 Wrap-Up 435
12 OOP: Polymorphism, Interfaces and Operator Overloading 441
12.1 Introduction 442 12.2 Polymorphism Examples 444 12.3 Demonstrating Polymorphic Behavior 445 12.4 Abstract Classes and Methods 448 12.5 Case Study: Payroll System Using Polymorphism 450
12.5.1 Creating Abstract Base Class Employee 451 12.5.2 Creating Concrete Derived Class SalariedEmployee 453 12.5.3 Creating Concrete Derived Class HourlyEmployee 455 12.5.4 Creating Concrete Derived Class CommissionEmployee 457 12.5.5 Creating Indirect Concrete Derived Class
BasePlusCommissionEmployee 458 12.5.6 Polymorphic Processing, Operator is and Downcasting 460
xii Contents
12.5.7 Summary of the Allowed Assignments Between Base-Class and Derived-Class Variables 465
12.6 sealed Methods and Classes 466 12.7 Case Study: Creating and Using Interfaces 466
12.7.1 Developing an IPayable Hierarchy 468 12.7.2 Declaring Interface IPayable 469 12.7.3 Creating Class Invoice 469 12.7.4 Modifying Class Employee to Implement Interface IPayable 471 12.7.5 Modifying Class SalariedEmployee for Use with IPayable 473 12.7.6 Using Interface IPayable to Process Invoices and Employees
Polymorphically 474 12.7.7 Common Interfaces of the .NET Framework Class Library 476
12.8 Operator Overloading 477 12.9 Wrap-Up 480
13 Exception Handling: A Deeper Look 486 13.1 Introduction 487 13.2 Example: Divide by Zero without Exception Handling 488 13.3 Example: Handling DivideByZeroExceptions and FormatExceptions 491
13.3.1 Enclosing Code in a try Block 493 13.3.2 Catching Exceptions 493 13.3.3 Uncaught Exceptions 494 13.3.4 Termination Model of Exception Handling 495 13.3.5 Flow of Control When Exceptions Occur 495
13.4 .NET Exception Hierarchy 496 13.4.1 Class SystemException 496 13.4.2 Determining Which Exceptions a Method Throws 497
13.5 finally Block 497 13.6 The using Statement 504 13.7 Exception Properties 505 13.8 User-Defined Exception Classes 509 13.9 Wrap-Up 513
14 Graphical User Interfaces with Windows Forms: Part 1 518
14.1 Introduction 519 14.2 Windows Forms 520 14.3 Event Handling 522
14.3.1 A Simple Event-Driven GUI 522 14.3.2 Auto-Generated GUI Code 524 14.3.3 Delegates and the Event-Handling Mechanism 526 14.3.4 Another Way to Create Event Handlers 527 14.3.5 Locating Event Information 528
14.4 Control Properties and Layout 529
Contents xiii
14.5 Labels, TextBoxes and Buttons 533 14.6 GroupBoxes and Panels 536 14.7 CheckBoxes and RadioButtons 539 14.8 PictureBoxes 547 14.9 ToolTips 549 14.10 NumericUpDown Control 551 14.11 Mouse-Event Handling 553 14.12 Keyboard-Event Handling 556 14.13 Wrap-Up 559
15 Graphical User Interfaces with Windows Forms: Part 2 569
15.1 Introduction 570 15.2 Menus 570 15.3 MonthCalendar Control 579 15.4 DateTimePicker Control 580 15.5 LinkLabel Control 583 15.6 ListBox Control 587 15.7 CheckedListBox Control 591 15.8 ComboBox Control 594 15.9 TreeView Control 598 15.10 ListView Control 603 15.11 TabControl Control 609 15.12 Multiple Document Interface (MDI) Windows 614 15.13 Visual Inheritance 621 15.14 User-Defined Controls 626 15.15 Wrap-Up 630
16 Strings and Characters: A Deeper Look 638 16.1 Introduction 639 16.2 Fundamentals of Characters and Strings 640 16.3 string Constructors 641 16.4 string Indexer, Length Property and CopyTo Method 642 16.5 Comparing strings 643 16.6 Locating Characters and Substrings in strings 646 16.7 Extracting Substrings from strings 649 16.8 Concatenating strings 650 16.9 Miscellaneous string Methods 651 16.10 Class StringBuilder 652 16.11 Length and Capacity Properties, EnsureCapacity Method and Indexer
of Class StringBuilder 653 16.12 Append and AppendFormat Methods of Class StringBuilder 655 16.13 Insert, Remove and Replace Methods of Class StringBuilder 657 16.14 Char Methods 660
xiv Contents
16.15 (Online) Introduction to Regular Expressions 662 16.16 Wrap-Up 663
17 Files and Streams 669 17.1 Introduction 670 17.2 Data Hierarchy 670 17.3 Files and Streams 672 17.4 Classes File and Directory 673 17.5 Creating a Sequential-Access Text File 682 17.6 Reading Data from a Sequential-Access Text File 691 17.7 Case Study: Credit Inquiry Program 695 17.8 Serialization 701 17.9 Creating a Sequential-Access File Using Object Serialization 702 17.10 Reading and Deserializing Data from a Binary File 706 17.11 Wrap-Up 708
18 Searching and Sorting 715 18.1 Introduction 716 18.2 Searching Algorithms 717
18.2.1 Linear Search 717 18.2.2 Binary Search 721
18.3 Sorting Algorithms 726 18.3.1 Selection Sort 726 18.3.2 Insertion Sort 730 18.3.3 Merge Sort 734
18.4 Summary of the Efficiency of Searching and Sorting Algorithms 740 18.5 Wrap-Up 741
19 Data Structures 746 19.1 Introduction 747 19.2 Simple-Type structs, Boxing and Unboxing 747 19.3 Self-Referential Classes 748 19.4 Linked Lists 749 19.5 Stacks 762 19.6 Queues 766 19.7 Trees 769
19.7.1 Binary Search Tree of Integer Values 770 19.7.2 Binary Search Tree of IComparable Objects 777
19.8 Wrap-Up 782
20 Generics 789 20.1 Introduction 790 20.2 Motivation for Generic Methods 791 20.3 Generic-Method Implementation 793
Contents xv
20.4 Type Constraints 796 20.5 Overloading Generic Methods 798 20.6 Generic Classes 799 20.7 Wrap-Up 808
21 Collections 814 21.1 Introduction 815 21.2 Collections Overview 815 21.3 Class Array and Enumerators 818 21.4 Nongeneric Collections 821
21.4.1 Class ArrayList 821 21.4.2 Class Stack 826 21.4.3 Class Hashtable 828
21.5 Generic Collections 833 21.5.1 Generic Class SortedDictionary 834 21.5.2 Generic Class LinkedList 836
21.6 Covariance and Contravariance for Generic Types 840 21.7 Wrap-Up 843
22 Databases and LINQ 849 22.1 Introduction 850 22.2 Relational Databases 851 22.3 A Books Database 852 22.4 LINQ to Entities and the ADO.NET Entity Framework 856 22.5 Querying a Database with LINQ 857
22.5.1 Creating the ADO.NET Entity Data Model Class Library 858 22.5.2 Creating a Windows Forms Project and Configuring It to
Use the Entity Data Model 862 22.5.3 Data Bindings Between Controls and the Entity Data Model 864
22.6 Dynamically Binding Query Results 869 22.6.1 Creating the Display Query Results GUI 870 22.6.2 Coding the Display Query Results App 871
22.7 Retrieving Data from Multiple Tables with LINQ 874 22.8 Creating a Master/Detail View App 879
22.8.1 Creating the Master/Detail GUI 880 22.8.2 Coding the Master/Detail App 881
22.9 Address Book Case Study 883 22.9.1 Creating the Address Book App’s GUI 884 22.9.2 Coding the Address Book App 885
22.10 Tools and Web Resources 889 22.11 Wrap-Up 889
23 Web App Development with ASP.NET 897 23.1 Introduction 898
xvi Contents
23.2 Web Basics 899 23.3 Multitier App Architecture 900 23.4 Your First Web App 902
23.4.1 Building the WebTime App 904 23.4.2 Examining WebTime.aspx’s Code-Behind File 913
23.5 Standard Web Controls: Designing a Form 914 23.6 Validation Controls 918 23.7 Session Tracking 925
23.7.1 Cookies 926 23.7.2 Session Tracking with HttpSessionState 927 23.7.3 Options.aspx: Selecting a Programming Language 928 23.7.4 Recommendations.aspx: Displaying Recommendations
Based on Session Values 932 23.8 Case Study: Database-Driven ASP.NET Guestbook 933
23.8.1 Building a Web Form that Displays Data from a Database 935 23.8.2 Modifying the Code-Behind File for the Guestbook App 940
23.9 Online Case Study: ASP.NET AJAX 941 23.10 Online Case Study: Password-Protected Books Database App 942 23.11 Wrap-Up 942
Chapters on the Web 949
A Operator Precedence Chart 950
B Simple Types 952
C ASCII Character Set 954
Appendices on the Web 955
Index 957
Chapters 24–35 and Appendices D–G are PDF documents posted online at the book’s Companion Website (located at www.pearsonhighered.com/deitel/).
24 XML and LINQ to XML
25 Windows 8 UI and XAML
26 Windows 8 Graphics and Multimedia
Contents xvii
27 Building a Windows Phone 8 App
28 Asynchronous Programming with async and await
29 Web App Development with ASP.NET: A Deeper Look
30 Web Services
31 Building a Windows Azure™ Cloud Computing App
32 GUI with Windows Presentation Foundation
33 WPF Graphics and Multimedia
34 ATM Case Study, Part 1: Object-Oriented Design with the UML
35 ATM Case Study, Part 2: Implementing an Object- Oriented Design
D Number Systems
E UML 2: Additional Diagram Types
F Unicode®
G Using the Visual C# 2012 Debugger
This page intentionally left blank
Welcome to the Visual C#® 2012 computer programming language and the world of Mi- 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 the book’s essence. In this Preface we provide more details.
This book is appropriate for introductory course sequences based on the curriculum recommendations of two key professional organizations—the ACM and the IEEE. The examples are accessible to computer science, information technology, software engineering and 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 avail- able at www.deitel.com/books/vcsharp2012htp and www.pearsonhighered.com/deitel. 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 give you an informative, engaging, challenging and entertaining introduction to Visual C#. If you have questions, we’re easy to reach at deitel@deitel.com—we’ll respond promptly. For book updates, visit www.deitel.com/books/vcsharp2012htp, join our social media communities 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 at bit.ly/ ECMA334). Visual C# 2012 is Microsoft’s implementation of this standard.
Preface
xx Preface
• Modular multi-GUI treatment with Windows Forms, Windows 8 UI and WPF. The printed book features Windows Forms GUI; optional online chapters con- tain treatments of Windows 8 UI (user interface) and WPF GUI. Windows 8 UI apps are called Windows Store 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 Multi- media (Chapter 26) and WPF Graphics and Multimedia (Chapter 33).
• 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 da- tabase system). Microsoft stopped further development on LINQ to SQL in 2008 in favor of the newer and more robust LINQ to Entities and the ADO.NET Entity Framework, which we’ve switched to in this edition, keeping the 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 pres- ent the fundamentals of database programming. Chapters 22–23 and 29–30 use database and LINQ capabilities to build an address-book desktop app, a web- based guestbook app, a bookstore app and an airline reservation system app.
• 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 several apps, including a web-based guestbook that uses ASP.NET and the ADO .NET Entity Framework to store data in a database and display data in a web page. The chapter also discusses the IIS Express web server for testing your web apps on your 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 and touchscreen devices, enhanced security features and more. In Chapter 27, you’ll build a complete working Windows Phone 8 app and test it on the Windows Phone 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 can store data in the cloud.
• Asynchronous programming with async and await. Asynchronous programming is simplified in Visual C# 2012 with the new async and await capabilities. We introduce asynchronous programming with async and await in 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
Complete Code Examples xxi
that manipulates preexisting objects. You’ll develop your first customized classes and objects in Chapter 4. Presenting objects and classes early gets you “thinking about 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, polymor- phism and interfaces.
• Optional case study: Using the UML to develop an object-oriented design and Vi- sual C# implementation of an Automated Teller Machine (ATM). The UML™ (Unified Modeling Language™) is the industry-standard graphical language for modeling 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 design 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# implementa- tion. Students often report a “light bulb moment”—the case study helps them “tie 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
Account class Address book case study Airline reservation web-service Animating the width and
height of a video Applying transforms to a poly-
gon Array initializer ArrayList class BasePlusCommissionEmployee
class Binary search Blackjack game web-service Books database
Card shuffling and dealing CheckedListBox control ComboBox control CommissionEmployee class Common Windows 8 UI con-
trols Common WPF controls Compound interest calcula-
tions Counter-controlled repetition Craps dice game simulation Creating and using a text file Creating custom windows and
using timers
Credit-inquiry program Data binding Date class DateTimePicker control Defining gradients in XAML Dice rolling Directory class Document navigation using XNode
Drawing basic shapes Drawing polylines and poly-
gons Employee class File class
Fig. 1 | A small sample of the book’s hundreds of examples. (Part 1 of 2.)
xxii Preface
Interesting, 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 in- cludes simple recall of important terminology and concepts, identifying the errors in code samples, writing individual program statements, writing small portions of Visual C# classes, writing complete programs and implementing major proj- ects. Figure 2 lists a small sampling of the book’s hundreds of exercises, including 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 class Stack Generic class List GradeBook class Guestbook app HourlyEmployee class Session tracking in ASP.NET Invoice class IPayable interface Keyboard events LinkLabel control LINQ to Objects with arrays ListBox control Math tutor using web services Menus
NegativeNumberException
NumericUpDown control Object serialization Overloaded constructors PictureBox displaying images Reading sequential-access files Recursive Factorial method REST Web services with
JSON and XML SalariedEmployee class Searching directories with
LINQ Sequential search Sorting an array Stack unwinding
StringBuilder class TabControl
Text-to-speech and speech-to- text
Time class Toolbars TreeView control TV GUI showing GUI
customization Poll analysis Polymorphism demonstration Querying a database with
LINQ to Entities Queue class RadioButton control
Exercises
Airline Reservations System All Possible Three-Letter Words
from a Five-Letter Word Baseball Database App Binary Tree Traversals Blackjack Body Mass Index Calculator Bucket Sort Building Your Own Computer Calendar and Appointments Carbon Footprint Calculator
Card Shuffling and Dealing Car-Pool Savings Calculator Coin Tossing Complex Numbers Computer-Assisted Instruction Computerization of Health
Records Cooking with Healthier
Ingredients Credit Limit Calculator Dice Rolling
Ecofont Eight Queens Employee Class Enforcing Privacy with
Cryptography Enhanced Painter Factorials Fuzzy Dice Order Form Game of Craps Gas Mileage Generic 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.)
Illustrations and Figures xxiii
Illustrations and Figures Abundant tables, line drawings, UML diagrams, programs and program outputs are in- cluded. A sampling of these is shown in Figs. 3 and 4.
Guess the Number Game Invoice Class Knight’s Tour MDI Text Editor Nutrition Information Palindromes Phishing Scanner Phone-Book Web Service Pig Latin Polymorphic Banking Program
Using Account Hierarchy Pythagorean Triples
Quicksort Quiz App Rational Numbers Restaurant Bill Calculator Salary Calculator Sales Commissions Savings-Account Class Sieve of Eratosthenes Tortoise and Hare Simulation SMS Language Spam Scanner Story Writer
Student Poll Target-Heart-Rate Calculator Tax Plan Alternatives: The
“FairTax” Telephone-Number Word
Generator Tic-Tac-Toe Towers of Hanoi Turtle Graphics Typing Tutor Web-based Address Book World 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 library
Components and controls Custom-control creation DatePicker properties/event Doubly linked list Entity-relationship diagram
for the Books database
Escape sequences GroupBox properties HttpSessionState properties Implicit conversions between
simple types Increment and decrement
operators insertAtBack operation repre-
sented graphically insertAtFront operation rep-
resented graphically Interaction between a web-
service client and a SOAP web service
Interfaces of the .NET Frame- work Class Library
Keyboard events and event arguments
Keywords and contextual keywords
Linked list graphical representation
LINQ to XML class hierarchy Master/Detail app Math class methods Mouse events and event
arguments .NET Framework Class
Library namespaces Number of comparisons for
common Big O notations Object methods inherited by
all classes Polymorphic interface for the Employee hierarchy classes
Precedence of arithmetic oper- ators
removeFromBack operation represented graphically
removeFromFront operation represented graphically
Rules of forming structured apps
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.)
xxiv Preface
Other 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 en- courage instructors to begin covering LINQ technology early. Later in the book, we take a deeper look, using LINQ to Entities (Chapters 22–23 and 29–30) and LINQ 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’s public properties and public instance 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 struc- tures, generics and collections.
Searching and sorting algorithms with Big O values
Single-entry/single-exit sequence, selection and repetition statements
string format specifiers Three-tier architecture Traditional web app reloading
the page for every user interaction
Tree structure for the document article.xml
Validation app enhanced by ASP.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 a BalanceInquiry transaction Activity diagram for a Withdrawal transaction Classes in the ATM system with attributes and
operations Communication diagram of the ATM executing
a balance inquiry
Communication diagram for executing a balance inquiry
Sequence diagram that models a Withdrawal exe- cuting
Use case diagram for a modified version of our ATM system that also allows users to transfer money between accounts
Class diagram showing composition relation- ships of a class Car
Class diagram for the ATM system model including class Deposit
Activity diagram for a Deposit transaction Sequence diagram that models a Deposit executing
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.)
Companion Website xxv
• Integrated exception handling. We introduce exception handling early (Chapter 8, Arrays; Introduction to Exception Handling) to ensure that we do not access an array element outside the array’s bounds. Chapter 10, Classes and Objects: A Deeper Look, shows how to indicate an exception when a member function re- ceives an invalid argument. We cover the complete details of exception handling in Chapter 13, Exception Handling: A Deeper Look.
• 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 programmatically manipulate the elements of an XML document using LINQ to XML. XAML is an XML 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 on building a password-protected, web-based bookstore app. Also, we introduce in Chapter 29 ASP.NET AJAX controls and use them to add AJAX functionality to web 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 gen- erator web service that’s called by a math tutor app.
• WPF (Windows Presentation Foundation) GUI, graphics and multimedia. We extend the core book’s GUI coverage in optional online Chapters 32–33 with an introduction to Windows Presentation Foundation (WPF)—a XAML-based Mi- crosoft framework that preceded Windows 8 UI and integrates GUI, graphics and multimedia capabilities. We implement a painting app, a text editor, a color chooser, a book-cover viewer, a television video player, various animations, and speech synthesis and recognition apps.
Companion Website The printed book contains the core content (Chapters 1–23) for introductory course se- 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 PDF format on the book’s password-protected Companion Website at:
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.)
xxvi Preface
VideoNotes The 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. VideoNotes allow 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 to www.pearsonhighered.com/deitel/.
2. Scroll to Visual C# 2012 How to Program, 5/e and click Companion Website.
3. Click the Register button.
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 sub- scription is valid for twelve months upon activation and is not transferable. If this access code on your book has already been revealed, it may no longer be valid. If this is the case, click the Website Purchase link 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: async and await
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.)
Book 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 comput- ing fundamentals and Microsoft’s .NET platform. If you do not need to cover these fun- damentals, you should still cover the Painter app test-drive. The vast majority of the book’s 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, shows how to develop a simple GUI app that displays text and an image. We’ll look at Visual Studio 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, meth- ods and arrays) and introduce object-oriented programming. These chapters should be covered in order. Chapter 8 introduces exception handling with an example that demon- strates accessing an element outside an array’s bounds.
Object-Oriented Programming: A Deeper Look The chapters in this module of the book:
• Chapter 9, Introduction to LINQ and the List Collection
• 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 Design
provide a deeper look at object-oriented programming, including classes, objects, inheri- tance, polymorphism, interfaces and exception handling. Chapter 9, Introduction to LINQ and the List Collection, introduces Microsoft’s Language Integrated Query (LINQ) tech- nology, which provides a uniform syntax for manipulating data from various data sources,
xxviii Preface
such as arrays, collections and, as you’ll see in later chapters, XML and databases. This chap- ter can be deferred, but it’s required for one example in Chapter 17 (Fig. 17.6) and many of the later chapters starting with Chapter 22, Databases and LINQ. Online Chapters 34–35 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 Forms Graphical User Interfaces (GUIs) There are now three GUI technologies in Windows—Windows Forms (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 Win- dows Forms for their classes, so we provide a two-chapter introduction to Windows Forms:
• 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 Windows Forms GUIs in several other print and online chap- ters. Most examples in Chapters 14–15 can be presented after Chapter 4. For those who wish 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).
Strings and Files We introduce strings beginning in Chapter 4 and use them throughout the book. Chapter 16, Strings and Characters: A Deeper Look, investigates strings in more depth. Chapter 17, Files and Streams, introduces text-file processing and object-serialization for input/output of entire objects. Chapter 16 can be presented at any point after Chapter 4. Chapter 17 requires C#, object-oriented programming and Windows Forms 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 im- plement customized searching, sorting and data structures capabilities, we provide Chapters 18–20, which require the concepts presented in Chapters 3–8 and 10–13.
Databases and an Introduction to Web App Development Chapter 22, Databases and LINQ, introduces database app development using the ADO.NET Entity Framework and LINQ to Entities. The chapter’s examples require C#, object-oriented programming and Windows Forms concepts presented in Chapters 3–14. Chapter 23, Web App Development with ASP.NET, introduces web app development.
Book Overview and Chapter Dependencies xxix
The last example in this chapter requires the LINQ and database techniques presented in Chapter 22.
Extensible Markup Language (XML) Chapter 24, XML and LINQ to XML, introduces XML, which is used in several later chap- ters. The first few sections of this chapter are required to understand the XAML markup that’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 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 develop- ment. These chapters can be used only on computers running Windows 8 and depend on event-handling concepts that are presented in Chapter 14, and the introduction to XML at the beginning of Chapter 24 (see Section 24.1 for details). Developing a Windows Phone 8 app is similar to developing a Windows 8 UI app.
Asynchronous Programming Chapter 28, Asynchronous Programming with async and await, demonstrates .NET’s and 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 ser- vices, including a case study on cloud computing with Windows Azure. Chapters 30 and 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 chap- 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 the beginning of Chapter 24.
xxx Preface
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 more executions showing program inputs and outputs. In the few cases where we show a code snippet, to ensure correctness we first tested it in a complete working program then copied the code from the program and pasted it into the book.
Syntax Shading. For readability, we syntax shade the code, similar to the way most inte- grated-development environments and code editors syntax color the code. Our syntax- shading conventions are:
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 Helvetica font (for example, the File menu) and Visual C# program text in the Lucida font (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 as- pects of program development. These tips and practices represent the best we’ve gleaned from a combined seven decades of programming and teaching experience.
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 pro- duce programs that are clearer, more understandable and more maintainable.
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.
Performance Tip These tips highlight opportunities for making your programs run faster or minimizing the amount of memory that they occupy.
Portability Tip The Portability Tips help you write code that will run on a variety of platforms.
Obtaining 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 re- 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 member, contact your Pearson representative or visit www.pearsonhighered.com/ educator/replocator/. Exercise Solutions are not provided for “project” exercis- es. Check out our Programming Projects Resource Center for lots of additional ex- ercise and project possibilities:
• 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.
Look-and-Feel Observation These observations help you design attractive, user-friendly graphical user interfaces that conform to industry norms.
www.microsoft.com/visualstudio/eng/products/ visual-studio-express-products
www.deitel.com/ProgrammingProjects
xxxii Preface
Microsoft DreamSpark™ Professional Developer and Designer Tools for Students Microsoft provides many of its professional developer tools to students for free via a pro- gram called DreamSpark (www.dreamspark.com). See the website for details on verifying your student status so you take advantage of this program.
Acknowledgments We’d like to thank Abbey Deitel and Barbara Deitel of Deitel & Associates, Inc. for long hours devoted to this project. Abbey co-authored this Preface and Chapter 1 and she and Barbara 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 Tracy Johnson, Executive Editor, Computer Science. Carole Snyder did an extraordinary job recruiting the book’s reviewers and managing the review process. Bob Engelhardt did a wonderful job bringing the book to publication.
Reviewers We wish to acknowledge the efforts of our reviewers. The book was scrutinized by aca- demics teaching C# courses and industry experts. They provided countless suggestions for improving the presentation. Any remaining flaws in the book are our own.
Fifth Edition Reviewers: Shay Friedman (Microsoft Visual C# MVP), Octavio Her- nandez (Microsoft Certified Solutions Developer), Stephen Hustedde (South Mountain College), 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 El Paso), 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 Micro- soft), Bashar Lulu (INETA Country Leader, Arabian Gulf), John McIlhinney (Spatial Intelligence; Microsoft MVP 2008 Visual Developer, Visual Basic), Ged Mead (Microsoft Visual Basic MVP, DevCity.net), Anand Mukundan (Architect, Polaris Software Lab Ltd.), Timothy Ng (Microsoft), Akira Onishi (Microsoft), Joe Stagner (Senior Program Manager, Developer Tools & Platforms), Erick Thompson (Microsoft), Jesús Ubaldo Quevedo-Torrero (University of Wisconsin–Parkside, Department of Computer Science) and Zijiang Yang (Western Michigan University).
As you read the book, we’d sincerely appreciate your comments, criticisms and sug- gestions for improving the text. Please address all correspondence to:
deitel@deitel.com
About the Authors xxxiii
We’ll respond promptly. We really enjoyed writing this book—we hope you enjoy reading it!
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, the National Severe Storm Laboratory, White Sands Missile Range, Rogue Wave Software, Boeing, SunGard Higher Education, Nortel Networks, Puma, iRobot, Invensys and many more. 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 the Chairman of the Computer Science Department at Boston College before founding Deitel & Associates, Inc., in 1991 with his son, Paul Deitel. The Deitels’ publications have earned international recognition, with translations published in Chinese, Korean, Japa- nese, German, Russian, Spanish, French, Polish, Italian, Portuguese, Greek, Urdu and Turkish. 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 internationally recognized authoring and corporate training organization, specializing in computer pro- gramming languages, object technology, mobile app development and Internet and web software technology. The company’s training clients include many of the world’s largest companies, government agencies, branches of the military, and academic institutions. The company offers instructor-led training courses delivered at client sites worldwide on major programming languages and platforms, including Visual C#®, Visual Basic®, Visual C++®, 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
xxxiv Preface
Through 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-mail deitel@deitel.com.
Individuals wishing to purchase Deitel books and LiveLessons video training can do so through www.deitel.com. Bulk orders by corporations, the government, the military and academic institutions should be placed directly with Pearson. For more information, visit
deitel@deitel.com
www.deitel.com/training
www.informit.com/store/sales.aspx
This section contains information you should review before using this book and instruc- tions to ensure that your computer is set up properly for use with this book.
Font and Naming Conventions We use fonts to distinguish between features, such as menu names, menu items, and other elements that appear in the program-development environment. Our convention is to em- phasize IDE features in a sans-serif bold Helvetica font (for example, Properties window) and to emphasize program text in a sans-serif Lucida font (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 at www.microsoft.com/express. The Express Editions are 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 meets the 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, .cs or .png). Your system’s settings may need to be adjusted to display file-name extensions. Follow these steps to configure your Windows 7 computer:
1. In the Start menu, select All Programs, then Accessories, then Windows Explorer.
2. Press Alt to display the menu bar, then select Folder Options… from Windows Ex- plorer’s Tools menu.
3. In the dialog that appears, select the View tab.
4. In the Advanced settings: pane, uncheck the box to the left of the text Hide ex- tensions for known file types. [Note: If this item is already unchecked, no action 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
xxxvi Before You Begin
Follow these steps to configure your Windows 8 computer:
1. On the Start screen, click the Desktop tile to switch to the desktop.
2. On the task bar, click the File Explorer icon to open the File Explorer.
3. Click the View tab, then ensure that the File name extensions checkbox is checked.
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 to www.deitel.com and click the Register 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 only account-management e-mails unless you register separately for our free e-mail newsletter at www.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 to www.deitel.com and sign in.
Next, go to www.deitel.com/books/vcsharp2012htp/. Click the Examples link to download the ZIP archive file to your computer. Write down the location where you save the file—most browsers will save the file into your Downloads folder.
Throughout the book, steps that require you to access our example code on your com- puter assume that you’ve extracted the examples from the ZIP file and placed them at C:\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’s contents using tools such as WinZip (www.winzip.com), 7-zip (www.7-zip.org) or the built-in capabilities of Windows Explorer on Window 7 or File Explorer on Windows 8.
Visual Studio Theme Visual Studio 2012 has a Dark theme (the default) and a Light theme. The screen captures shown in this book use the Light theme, which is more readable in print. If you’d like to switch to the Light theme, in the TOOLS menu, select Options… to display the Options di- alog. In the left column, select Environment, then select Light under Color theme. Keep the Options dialog 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 the IDE display line numbers, expand the Text Editor node in the left pane then select All Lan- guages. On the right, check the Line numbers checkbox. Next, expand the C# node in the left pane and select Tabs. Make sure that the option Insert spaces is selected. Enter 3 for both the Tab size and Indent size fields. Any new code you add will now use three spaces for each level of indentation. Click OK to save your settings.
Miscellaneous Notes • Some people like to change the workspace layout in the development tools. You
can return the tools to their default layouts by selecting Window > Reset Window Layout.
www.deitel.com/books/vcsharp2012htp/
Before You Begin xxxvii
• Many of the menu items we use in the book have corresponding icons shown with each menu item in the menus. Many of the icons also appear on one of the toolbars at the top of the development environment. As you become familiar with these icons, you can use the toolbars to help speed up your development time. Similarly, many of the menu items have keyboard shortcuts (also shown with each 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!
This page intentionally left blank
1Introduction to Computers,the Internet and Visual C# The chief merit of language is clearness. —Galen
Our life is frittered away with detail. . . . Simplify, simplify. —Henry David Thoreau
Man is still the most extraordinary computer of all. —John F. Kennedy
O b j e c t i v e s In this chapter you’ll learn:
� Basic hardware, software and data concepts.
� The different types of programming languages.
� The history of the Visual C# programming language and the Windows operating system.
� What cloud computing with Windows Azure is.
� Basics of object technology.
� The history of the Internet and the World Wide Web.
� The parts that Windows 8, .NET 4.5, Visual Studio 2012 and Visual C# 2012 play in the Visual C# ecosystem.
� To test-drive a Visual C# 2012 drawing app.
2 Chapter 1 Introduction to Computers, the Internet and Visual C#
1.1 Introduction Welcome to Visual C# 2012 which, from this point forward, we’ll refer to simply as C#.1
C# is a powerful computer programming language that’s appropriate for building substan- tial information systems.
You’re already familiar with the powerful tasks computers perform. Using this text- book, you’ll write instructions commanding computers to perform those kinds of tasks and you’ll prepare yourself to address new challenges.
Computers process data under the control of sequences of instructions called com- puter programs. These programs guide the computer through actions specified by people called computer programmers. The programs that run on a computer are referred to as software. In this book, you’ll learn object-oriented programming—today’s key program- ming methodology that’s enhancing programmer productivity, and reducing software development costs. You’ll create many software objects that model both abstract and real- world things. And you’ll build C# apps for a variety of environments including the desktop—and new to this edition of the book—mobile devices like smartphones and tablets, and even “the cloud.”
1.2 Hardware and Moore’s Law A computer consists of various devices referred to as hardware, such as the keyboard, screen, mouse, hard disks, memory, DVD drives and processing units. Every year or two,
1.1 Introduction 1.2 Hardware and Moore’s Law 1.3 Data Hierarchy 1.4 Computer Organization 1.5 Machine Languages, Assembly
Languages and High-Level Languages 1.6 Object Technology 1.7 Internet and World Wide Web 1.8 C#
1.8.1 Object-Oriented Programming 1.8.2 Event-Driven Programming 1.8.3 Visual Programming 1.8.4 An International Standard; Other C#
Implementations 1.8.5 Internet and Web Programming 1.8.6 Introducing async/await 1.8.7 Other Key Contemporary
Programming Languages 1.9 Microsoft’s .NET
1.9.1 .NET Framework 1.9.2 Common Language Runtime
1.9.3 Platform Independence 1.9.4 Language Interoperability
1.10 Microsoft’s Windows® Operating System
1.11 Windows Phone 8 for Smartphones 1.11.1 Selling Your Apps in the Windows
Phone Marketplace 1.11.2 Free vs. Paid Apps 1.11.3 Testing Your Windows Phone Apps
1.12 Windows Azure™ and Cloud Computing
1.13 Visual Studio Express 2012 Integrated Development Environment
1.14 Painter Test-Drive in Visual Studio Express 2012 for Windows Desktop
1.15 Painter Test-Drive in Visual Studio Express 2012 for Windows 8
Self-Review Exercises | Answers to Self-Review Exercises | Exercises | Making a Difference Exercises
1. The name C#, pronounced “C-sharp,” is based on the musical # notation for “sharp” notes.
1.3 Data Hierarchy 3
the capacities of computer hardware have approximately doubled inexpensively. This re- markable trend often is called Moore’s Law, named for the person who identified it, Gor- don Moore, co-founder of Intel—the leading manufacturer of the processors in today’s computers and embedded systems, such as smartphones, appliances, game controllers, ca- ble set-top boxes and automobiles.
Moore’s Law and related observations apply especially to
• the amount of memory that computers have for running programs and processing data
• the amount of secondary storage (such as hard disk storage) they have to hold programs and data over longer periods of time
• their processor speeds—the speeds at which computers execute their programs (i.e., do their work)
Similar growth has occurred in the communications field, in which costs have plum- meted as enormous demand for communications bandwidth (i.e., information-carrying capacity) has attracted intense competition. We know of no other fields in which tech- nology improves so quickly and costs fall so rapidly. Such phenomenal improvement is truly fostering the Information Revolution and creating significant career opportunities.
As a result of this continuing stream of technological advances, computers already can perform calculations and make logical decisions phenomenally faster than human beings can. Many of today’s personal computers can perform billions of calculations in one second—more than a human can perform in a lifetime. Supercomputers are already per- forming thousands of trillions (quadrillions) of instructions per second! The world’s fastest supercomputer—the Cray Titan—can perform over 17 quadrillion calculations per second—(17.59 petaflops)2—that’s more than 2 million calculations per second for every person on the planet! And—these “upper limits” are expanding quickly!
1.3 Data Hierarchy Data items processed by computers form a data hierarchy that becomes larger and more complex in structure as we progress from the simplest data items (called “bits”) to richer data items, such as characters, fields, and so on. Figure 1.1 illustrates a portion of the data hierarchy.
Bits The smallest data item in a computer can assume the value 0 or the value 1. Such a data item is called a bit (short for “binary digit”—a digit that can assume either of two values). It’s remarkable that the impressive functions performed by computers involve only the simplest manipulations of 0s and 1s—examining a bit’s value, setting a bit’s value and revers- ing a bit’s value (from 1 to 0 or from 0 to 1). We discuss binary numbers (and closely re- lated octal and hexadecimal numbers) in more detail in Appendix D, Number Systems.
Characters It’s tedious for people to work with data in the low-level form of bits. Instead, we prefer to work with decimal digits (0–9), letters (A–Z and a–z), and special symbols (e.g., $, @, %,
2. top500.org/lists/2012/11/.
4 Chapter 1 Introduction to Computers, the Internet and Visual C#
&, *, (, ), –, +, “, :, ? and / ). Digits, letters and special symbols are known as characters. The computer’s character set is the set of all the characters used to write programs and rep- resent data items on that device. Computers process only 1s and 0s, so every character is represented as a pattern of 1s and 0s. The Unicode character set contains characters for many of the world’s languages. C# supports several character sets, including 16-bit Uni- code® characters that are composed of two bytes—each byte is composed of eight bits. See Appendix B for more information on the ASCII (American Standard Code for Informa- tion Interchange) character set—the popular subset of Unicode that represents uppercase and lowercase letters in the English alphabet, digits and some common special characters.
Fields Just as characters are composed of bits, fields are composed of characters or bytes. A field is a group of characters or bytes that conveys meaning. For example, a field consisting of uppercase and lowercase letters could be used to represent a person’s name, and a field con- sisting of decimal digits could represent a person’s age.
Records Several related fields can be used to compose a record. In a payroll system, for example, the record for an employee might consist of the following fields (possible types for these fields are shown in parentheses):
Fig. 1.1 | Data hierarchy.
Tom Blue
Sally Black
Judy Green File
J u d y Field
Byte (ASCII character J)
Record
Iris Orange
Randy Red
01001010
1 Bit
Judy Green
1.3 Data Hierarchy 5
• Employee identification number (a whole number)
• Name (a string of characters)
• Address (a string of characters)
• Hourly pay rate (a number with a decimal point)
• Year-to-date earnings (a number with a decimal point)
• Amount of taxes withheld (a number with a decimal point)
Thus, a record is a group of related fields. In the preceding example, all the fields belong to the same employee. A company might have many employees and a payroll record for each.
Files A file is a group of related records. [Note: More generally, a file contains arbitrary data in arbitrary formats. In some operating systems, a file is viewed simply as a sequence of bytes— any organization of the bytes in a file, such as organizing the data into records, is a view created by the programmer.] It’s not unusual for an organization to have thousands or even millions of files, some containing billions or even trillions of characters of informa- tion. You’ll work with files in Chapter 17.
Database A database is a collection of data that’s organized for easy access and manipulation. The most popular database model is the relational database in which data is stored in simple tables. A table includes records and fields. For example, a table of students might include first name, last name, major, year, student ID number and grade point average fields. The data for each student is a record, and the individual pieces of information in each record are the fields. You can search, sort and otherwise manipulate the data based on its relation- ship to multiple tables or databases. For example, a university might use data from the stu- dent database in combination with data from databases of courses, on-campus housing, meal plans, etc. We discuss databases in Chapter 22.
Big Data The amount of data being produced worldwide is enormous and growing quickly. Accord- ing to IBM, approximately 2.5 quintillion bytes (2.5 exabytes) of data are created daily and 90% of the world’s data was created in just the past two years!3 According to an IDC study, approximately 1.8 zettabytes (equal to 1.8 trillion gigabytes) of data was used world- wide in 2011.4 Figure 1.2 shows relationships between byte measurements.
3. www-01.ibm.com/software/data/bigdata/.
Unit Bytes Which is approximately
1 kilobyte (KB) 1024 bytes 103 (1024 bytes exactly)
1 megabyte (MB) 1024 kilobytes 106 (1,000,000 bytes)
1 gigabyte (GB) 1024 megabytes 109 (1,000,000,000 bytes)
Fig. 1.2 | Byte measurements. (Part 1 of 2.)
4. www.emc.com/collateral/about/news/idc-emc-digital-universe-2011-infographic.pdf.
6 Chapter 1 Introduction to Computers, the Internet and Visual C#
1.4 Computer Organization Regardless of differences in physical appearance, computers can be envisioned as divided into various logical units or sections.
Input Unit This “receiving” section obtains information (data and computer programs) from input devices and places it at the disposal of the other units for processing. Most information is entered into computers through keyboards, touch screens and mouse devices. Other forms of input include receiving voice commands, scanning images and barcodes, reading from secondary storage devices (such as hard drives, DVD drives, Blu-ray Disc™ drives and USB flash drives—also called “thumb drives” or “memory sticks”), receiving video from a webcam or smartphone and having your computer receive information from the Internet (such as when you download videos from YouTube or e-books from Amazon). Newer forms of input include position data from GPS devices, and motion and orientation infor- mation from accelerometers in smartphones or game controllers (such as Microsoft® Ki- nect™, Nintendo’s Wii™ Remote and Sony’s PlayStation® Move).
Output Unit This “shipping” section takes information that the computer has processed and places it on various output devices to make it available for use outside the computer. Most infor- mation that’s output from computers today is displayed on screens; printed on paper (“go- ing green” discourages this); played as audio or video on PCs and media players (such as Apple® iPod®) and giant screens in sports stadiums; transmitted over the Internet or used to control other devices, such as robots, 3D printers and “intelligent” appliances.
Memory Unit This rapid-access, relatively low-capacity “warehouse” section retains information that’s entered through the input unit, making it immediately available for processing when need- ed. The memory unit also retains processed information until it can be placed on output devices by the output unit. Information in the memory unit is volatile—it’s typically lost when the computer’s power is turned off. The memory unit is often called either memory or primary memory—on desktop and notebook computers it commonly contains as much as 16 GB (GB stands for gigabytes; a gigabyte is approximately one billion bytes).
Arithmetic and Logic Unit (ALU) This “manufacturing” section performs calculations, such as addition, subtraction, multi- plication and division. It also contains the decision mechanisms that allow the computer,
1 terabyte (TB) 1024 gigabytes 1012 (1,000,000,000,000 bytes)
1 petabyte (PB) 1024 terabytes 1015 (1,000,000,000,000,000 bytes)
1 exabyte (EB) 1024 petabytes 1018 (1,000,000,000,000,000,000 bytes)
1 zettabyte (ZB) 1024 exabytes 1021 (1,000,000,000,000,000,000,000 bytes)
Unit Bytes Which is approximately
Fig. 1.2 | Byte measurements. (Part 2 of 2.)
1.5 Machine Languages, Assembly Languages and High-Level Languages 7
for example, to compare two items from the memory unit to determine whether they’re equal. In today’s systems, the ALU is usually implemented as part of the next logical unit, the CPU.
Central Processing Unit (CPU) This “administrative” section coordinates and supervises the operation of the other sec- tions. The CPU tells the input unit when information should be read into the memory unit, tells the ALU when information from the memory unit should be used in calculations and tells the output unit when to send information from the memory unit to certain output devices. Many of today’s computers have multiple CPUs and, hence, can perform many operations simultaneously. A multi-core processor implements multiple processors on a single “microchip”—a dual-core processor has two CPUs and a quad-core processor has four CPUs. Many of today’s desktop computers have quad-core processors that can execute bil- lions of instructions per second. In this book you’ll learn how to write programs that can keep all these processors running in parallel to get your computing tasks done faster.
Secondary Storage Unit This is the long-term, high-capacity “warehousing” section. Programs or data not actively being used by the other units normally are placed on secondary storage devices (such as your hard drive) until they’re again needed, possibly hours, days, months or even years lat- er. Information on secondary storage devices is persistent—it’s preserved even when the computer’s power is turned off. Secondary storage data takes much longer to access than information in primary memory, but the cost per unit of secondary storage is much less than that of primary memory. Examples of secondary storage devices include CD drives, DVD drives and flash drives, some of which can hold up to 768 GB. Typical hard drives on desktop and notebook computers can hold up to 2 TB (TB stands for terabytes; a tera- byte is approximately one trillion bytes). New to this edition, you’ll see that storage in “the cloud” can be viewed as additional secondary storage accessible by your C# apps.
1.5 Machine Languages, Assembly Languages and High- Level Languages Programmers write instructions in various programming languages (such as C#), some di- rectly understandable by computers and others requiring intermediate translation steps.
Machine Languages Any computer can directly understand only its own machine language, defined by its hard- ware architecture. Machine languages generally consist of numbers, ultimately reduced to 1s and 0s. Such languages are cumbersome for humans, who prefer words like “add” and “subtract” to indicate the operations to be performed, so the machine language numeric versions of these instructions were referred to as code. The term “code” has become more broadly used and now refers to the program instructions in all levels of language.
Assembly Languages and Assemblers Machine language was simply too slow and tedious to work with. Instead, programmers began using English-like abbreviations to represent elementary operations. These abbrevi- ations form the basis of assembly languages. Translator programs called assemblers convert assembly-language code to machine code quickly. Although assembly-language code is
8 Chapter 1 Introduction to Computers, the Internet and Visual C#
clearer to humans, it’s incomprehensible to computers until translated to machine lan- guage code.
High-Level Languages, Compilers and Interpreters To speed the programming process even further, high-level languages were developed in which single statements could be written to accomplish substantial tasks. High-level lan- guages, such as C#, Visual Basic, C++, C, Objective-C and Java, allow you to write instruc- tions that look almost like everyday English and contain commonly used mathematical expressions. Translator programs called compilers convert high-level language code into machine language code.
The process of compiling a large high-level language program into machine language can take a considerable amount of computer time. Interpreter programs were developed to execute high-level language programs directly (without the need for compilation), although more slowly than compiled programs.
1.6 Object Technology C# is an object-oriented programming language. In this section we’ll introduce the basics of object technology.
Building software quickly, correctly and economically remains an elusive goal at a time when demands for new and more powerful software are soaring. Objects, or more precisely the classes objects come from, are essentially reusable software components. There are date objects, time objects, audio objects, video objects, automobile objects, people objects, etc. Almost any noun can be reasonably represented as a software object in terms of attributes (e.g., name, color and size) and behaviors (e.g., calculating, moving and com- municating). Software developers have discovered that using a modular, object-oriented design and implementation approach can make software-development groups much more productive than was possible with earlier techniques—object-oriented programs are often easier to understand, correct and modify.
The Automobile as an Object Let’s begin with a simple analogy. Suppose you want to drive a car and make it go faster by pressing its accelerator pedal. What must happen before you can do this? Well, before you can drive a car, someone has to design it. A car typically begins as engineering drawings, similar to the blueprints that describe the design of a house. These drawings include the design for an accelerator pedal. The pedal hides from the driver the complex mechanisms that actually make the car go faster, just as the brake pedal hides the mechanisms that slow the car, and the steering wheel hides the mechanisms that turn the car. This enables people with little or no knowledge of how engines, braking and steering mechanisms work to drive a car easily.
Before you can drive a car, it must be built from the engineering drawings that describe it. A completed car has an actual accelerator pedal to make the car go faster, but even that’s not enough—the car won’t accelerate on its own (we hope), so the driver must press the pedal to accelerate the car.
Methods and Classes Let’s use our car example to introduce some key object-oriented programming concepts. Performing a task in a program requires a method. The method houses the program state-
1.6 Object Technology 9
ments that actually perform the task. It hides these statements from its user, just as a car’s accelerator pedal hides from the driver the mechanisms of making the car go faster. In ob- ject-oriented programming languages, we create a program unit called a class to house the set of methods that perform the class’s tasks. For example, a class that represents a bank account might contain one method to deposit money to an account, another to withdraw money from an account and a third to inquire what the account’s current balance is. A class that represents a car might contain methods for accelerating, braking and turning. A class is similar in concept to a car’s engineering drawings, which house the design of an accel- erator pedal, steering wheel, and so on.
Making Objects from Classes Just as someone has to build a car from its engineering drawings before you can actually drive a car, you must build an object from a class before a program can perform the tasks that the class’s methods define. The process of doing this is called instantiation. An object is then referred to as an instance of its class.
Reuse Just as a car’s engineering drawings can be reused many times to build many cars, you can reuse a class many times to build many objects. Reuse of existing classes when building new classes and programs saves time and effort. Reuse also helps you build more reliable and ef- fective systems, because existing classes and components often have gone through extensive testing (to locate problems), debugging (to correct those problems) and performance tuning. Just as the notion of interchangeable parts was crucial to the Industrial Revolution, reusable classes are crucial to the software revolution that’s been spurred by object technology.
Messages and Method Calls When you drive a car, pressing its gas pedal sends a message to the car to perform a task— that is, to go faster. Similarly, you send messages to an object. Each message is implemented as a method call that tells a method of the object to perform its task. For example, a pro- gram might call a particular bank-account object’s deposit method to increase the account’s balance.
Attributes and Instance Variables A car, besides having capabilities to accomplish tasks, also has attributes, such as its color, its number of doors, the amount of gas in its tank, its current speed and its record of total miles driven (i.e., its odometer reading). Like its capabilities, the car’s attributes are repre- sented as part of its design in its engineering diagrams (which, for example, include an odometer and a fuel gauge). As you drive an actual car, these attributes are carried along with the car. Every car maintains its own attributes. For example, each car knows how much gas is in its own gas tank, but not how much is in the tanks of other cars.
An object, similarly, has attributes that it carries along as it’s used in a program. These attributes are specified as part of the object’s class. For example, a bank-account object has a balance attribute that represents the amount of money in the account. Each bank-
Software Engineering Observation 1.1 Use a building-block approach to creating your programs. Avoid reinventing the wheel— use existing pieces wherever possible. This software reuse is a key benefit of object-oriented programming.
10 Chapter 1 Introduction to Computers, the Internet and Visual C#
account object knows the balance in the account it represents, but not the balances of the other accounts in the bank. Attributes are specified by the class’s instance variables.
Encapsulation Classes encapsulate (i.e., wrap) attributes and methods into objects—an object’s attributes and operations are intimately related. Objects may communicate with one another, but they’re normally not allowed to know how other objects are implemented—implementa- tion details are hidden within the objects themselves. This information hiding, as we’ll see, is crucial to good software engineering.
Inheritance A new class of objects can be created quickly and conveniently by inheritance—the new class absorbs the characteristics of an existing class, possibly customizing them and adding unique characteristics of its own. In our car analogy, an object of class “convertible” cer- tainly is an object of the more general class “automobile,” but more specifically, the roof can be raised or lowered.
Object-Oriented Analysis and Design (OOAD) Soon you’ll be writing programs in C#. Perhaps, like many programmers, you’ll simply turn on your computer and start typing. This approach may work for small programs (like the ones we present in the early chapters of this book), but what if you were asked to create a software system to control thousands of automated teller machines for a major bank? Or suppose you were assigned to work on a team of thousands of software developers building the next U.S. air traffic control system? For projects so large and complex, you should not simply sit down and start writing programs.
To create the best solutions, you should follow a detailed analysis process for deter- mining your project’s requirements (i.e., defining what the system is supposed to do) and developing a design that satisfies them (i.e., deciding how the system should do it). Ideally, you’d go through this process and carefully review the design (and have your design reviewed by other software professionals) before writing any code. If this process involves analyzing and designing your system from an object-oriented point of view, it’s called an object-oriented analysis and design (OOAD) process. Languages like C# are object ori- ented. Programming in such a language, called object-oriented programming (OOP), allows you to implement an object-oriented design as a working system.
The UML (Unified Modeling Language) Though many different OOAD processes exist, a single graphical language for communi- cating the results of any OOAD process—known as the Unified Modeling Language (UML)—is now the most widely used graphical scheme for modeling object-oriented sys- tems. We present our first simple UML diagrams in Chapters 4 and 5, then use them in our deeper treatment of object-oriented programming through Chapter 12. In our option- al ATM Software Engineering Case Study in Chapters 34–35 we present a simple subset of the UML’s features as we guide you through a simple object-oriented design experience.
1.7 Internet and World Wide Web In the late 1960s, ARPA—the Advanced Research Projects Agency of the United States De- partment of Defense—rolled out plans to network the main computer systems of approxi-
1.7 Internet and World Wide Web 11
mately a dozen ARPA-funded universities and research institutions. The computers were to be connected with communications lines operating at a then-stunning 56 Kbps (1 Kbps is equal to 1,024 bits per second), at a time when most people (of the few who even had net- working access) were connecting over telephone lines to computers at a rate of 110 bits per second. Academic research was about to take a giant leap forward. ARPA proceeded to im- plement what quickly became known as the ARPAnet, the precursor to today’s Internet.
Things worked out differently from the original plan. Although the ARPAnet enabled researchers to network their computers, its main benefit proved to be the capability for quick and easy communication via what came to be known as electronic mail (e-mail). This is true even on today’s Internet, with e-mail, instant messaging, file transfer and social media such as Facebook and Twitter, enabling billions of people worldwide to communi- cate quickly and easily.
The protocol (set of rules) for communicating over the ARPAnet became known as the Transmission Control Protocol (TCP). TCP ensured that messages, consisting of sequentially numbered pieces called packets, were properly routed from sender to receiver, arrived intact and were assembled in the correct order.
The Internet: A Network of Networks In parallel with the early evolution of the Internet, organizations worldwide were imple- menting their own networks for both intraorganization (that is, within an organization) and interorganization (that is, between organizations) communication. A huge variety of networking hardware and software appeared. One challenge was to enable these different networks to communicate with each other. ARPA accomplished this by developing the In- ternet Protocol (IP), which created a true “network of networks,” the current architecture of the Internet. The combined set of protocols is now called TCP/IP.
Businesses rapidly realized that by using the Internet, they could improve their oper- ations and offer new and better services to their clients. Companies started spending large amounts of money to develop and enhance their Internet presence. This generated fierce competition among communications carriers and hardware and software suppliers to meet the increased infrastructure demand. As a result, bandwidth—the information-carrying capacity of communications lines—on the Internet has increased tremendously, while hardware costs have plummeted.
The World Wide Web: Making the Internet User-Friendly The World Wide Web (simply called “the web”) is a collection of hardware and software associated with the Internet that allows computer users to locate and view multimedia- based documents (documents with various combinations of text, graphics, animations, au- dios and videos) on almost any subject. The introduction of the web was a relatively recent event. In 1989, Tim Berners-Lee of CERN (the European Organization for Nuclear Re- search) began to develop a technology for sharing information via “hyperlinked” text doc- uments. Berners-Lee called his invention the HyperText Markup Language (HTML). He also wrote communication protocols such as HyperText Transfer Protocol (HTTP) to form the backbone of his new hypertext information system, which he referred to as the World Wide Web.
In 1994, Berners-Lee founded an organization, called the World Wide Web Consor- tium (W3C, www.w3.org), devoted to developing web technologies. One of the W3C’s