This is an electronic version of the print textbook. Due to electronic rights restrictions,
some third party content may be suppressed. Editorial review has deemed that any suppressed
content does not materially affect the overall learning experience. The publisher reserves the right
to remove content from this title at any time if subsequent rights restrictions require it. For
valuable information on pricing, previous editions, changes to current editions, and alternate
formats, please visit www.cengage.com/highered to search by ISBN#, author, title, or keyword for
materials in your areas of interest.
MICROSOFT®
VISUAL C#® 2010
AN INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
JOYCE FARRELL
Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States
FOURTH EDITION
© 2011 Course Technology, Cengage Learning
ALL RIGHTS RESERVED. No part of this work covered by the copyright
herein may be reproduced, transmitted, stored, or used in any form or by
any means—graphic, electronic, or mechanical, including but not limited
to photocopying, recording, scanning, digitizing, taping, Web distribution,
information networks, or information storage and retrieval systems, except
as permitted under Section 107 or 108 of the 1976 United States Copyright
Act—without the prior written permission of the publisher.
Library of Congress Control Number: 2010930061
ISBN-13: 978-0-538-47951-6
ISBN-10: 0-538-47951-5
Course Technology
20 Channel Center Street
Boston, MA 02210
USA
Cengage Learning is a leading provider of customized learning solutions
with offi ce locations around the globe, including Singapore, the United
Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local offi ce at:
www.cengage.com/global
Cengage Learning products are represented in Canada by
Nelson Education, Ltd.
To learn more about Course Technology, visit www.cengage.com/
coursetechnology
To learn more about Cengage Learning, visit www.cengage.com
Purchase any of our products at your local college store or at our preferred
online store www.cengagebrain.com
Some of the product names and company names used in this book have
been used for identifi cation purposes only and may be trademarks or
registered trademarks of their respective manufacturers and sellers.
Any fi ctional data related to people, companies, or URLs used throughout
this book is intended for instructional purposes only. At the time this book
was printed, any such data was fi ctional and not belonging to any real
people or companies.
Course Technology, a part of Cengage Learning, reserves the right to revise this
publication and make changes from time to time in its content without notice.
The programs in this book are for instructional purposes only. They have
been tested with care, but are not guaranteed for any particular intent
beyond educational purposes. The author and the publisher do not off er
any warranties or representations, nor do they accept any liabilities with
respect to the programs.
Microsoft® Visual C#® 2010: An
Introduction to Object-Oriented
Programming, Fourth Edition
Joyce Farrell
Publisher: Nicole Pinard
Executive Editor: Marie Lee
Acquisitions Editor: Amy Jollymore
Senior Product Manager: Alyssa Pratt
Development Editor: Dan Seiter
Content Project Manager: Lisa Weidenfeld
Manufacturing Buyer: Julio Esperas
Proofreader: Brandy Lilly
Copyeditor: Michael Beckett
Indexer: Sharon Hilgenberg
Art Director: Faith Brosnan
Text Designer: Shawn Girsberger
Cover Photo: iStockphoto.com/Dimitrije
Cover Designer: Bruce Bond
Editorial Assistant: Jacqueline Lacaire
Art Director: Marissa Falco
Marketing Manager: Adam Marsh
Quality Assurance: Chris Scriver and
Danielle Shaw
Compositor: Integra
For product information and technology assistance, contact us at
Cengage Learning Customer & Sales Support, 1-800-354-9706
For permission to use material from this text or product,
submit all requests online at www.cengage.com/permissions
Further permissions questions can be e-mailed to
Printed in the United States of America
1 2 3 4 5 6 7 14 13 12 11 10
Brief Contents
Preface . . . . . . . . . . . . . . . . . xv
CHAPTER 1 A First Program Using C# . . . . . . . . . 1
CHAPTER 2 Using Data . . . . . . . . . . . . . . . . 49
CHAPTER 3 Using GUI Objects and the Visual
Studio IDE . . . . . . . . . . . . . . . 103
CHAPTER 4 Making Decisions . . . . . . . . . . . . 142
CHAPTER 5 Looping . . . . . . . . . . . . . . . . 194
CHAPTER 6 Using Arrays . . . . . . . . . . . . . . 232
CHAPTER 7 Using Methods . . . . . . . . . . . . . 273
CHAPTER 8 Advanced Method Concepts. . . . . . . . 315
CHAPTER 9 Using Classes and Objects . . . . . . . . 354
CHAPTER 10 Introduction to Inheritance . . . . . . . . 427
CHAPTER 11 Exception Handling . . . . . . . . . . . 490
CHAPTER 12 Using Controls . . . . . . . . . . . . . 540
CHAPTER 13 Handling Events . . . . . . . . . . . . . 606
CHAPTER 14 Files and Streams . . . . . . . . . . . . 656
CHAPTER 15 Using LINQ to Access Data in C#
Programs. . . . . . . . . . . . . . . . 708
iii
iv
BRIEF CONTENTS
APPENDIX A Operator Precedence And Associativity. . . 764
APPENDIX B Understanding Numbering Systems
and Computer Codes. . . . . . . . . . . 766
APPENDIX C Using The IDE Editor. . . . . . . . . . . 775
Glossary . . . . . . . . . . . . . . . . 779
Index . . . . . . . . . . . . . . . . . 799
Contents
Preface . . . . . . . . . . . . . . . . . xv
CHAPTER 1 A First Program Using C# . . . . . . . . . 1
Programming . . . . . . . . . . . . . . . . . . . . . . . 2
Procedural and Object-Oriented Programming . . . . . . . . 4
Features of Object-Oriented Programming Languages . . . . . 7
The C# Programming Language . . . . . . . . . . . . . . . 9
Writing a C# Program That Produces Output . . . . . . . . .10
Selecting Identifiers . . . . . . . . . . . . . . . . . . . .14
Improving Programs by Adding Comments and
Using the System Namespace . . . . . . . . . . . . . .18
Adding Program Comments . . . . . . . . . . . . . . . .18
Using the System Namespace . . . . . . . . . . . . . .19
Writing and Compiling a C# Program . . . . . . . . . . . .21
Compiling Code from the Command Prompt . . . . . . . .21
Compiling Code within the Visual Studio IDE . . . . . . . .24
You Do It . . . . . . . . . . . . . . . . . . . . . . . . .26
Entering a Program into an Editor . . . . . . . . . . . . .26
Compiling and Executing a Program from the
Command Line . . . . . . . . . . . . . . . . . . . . .27
Compiling and Executing a Program Using
the Visual Studio IDE . . . . . . . . . . . . . . . . . .29
Deciding Which Method to Use . . . . . . . . . . . . . .35
Adding Comments to a Program. . . . . . . . . . . . . .36
Chapter Summary . . . . . . . . . . . . . . . . . . . . .37
Key Terms . . . . . . . . . . . . . . . . . . . . . . . .38
Review Questions . . . . . . . . . . . . . . . . . . . . .42
Exercises . . . . . . . . . . . . . . . . . . . . . . . . .46
CHAPTER 2 Using Data . . . . . . . . . . . . . . . . 49
Declaring Variables . . . . . . . . . . . . . . . . . . . .50
Displaying Variable Values . . . . . . . . . . . . . . . . .54
v
vi
CONTENTS
Using the Integral Data Types. . . . . . . . . . . . . . . .58
Using Floating-Point Data Types . . . . . . . . . . . . . . .60
Formatting Floating-Point Values. . . . . . . . . . . . . .61
Using Arithmetic Operators . . . . . . . . . . . . . . . . .63
Using Shortcut Arithmetic Operators. . . . . . . . . . . .65
Using the bool Data Type . . . . . . . . . . . . . . . . .67
Understanding Numeric Type Conversion. . . . . . . . . . .68
Using the char Data Type . . . . . . . . . . . . . . . . .71
Using the string Data Type . . . . . . . . . . . . . . . .73
Defining Named Constants . . . . . . . . . . . . . . . . .77
Working with Enumerations . . . . . . . . . . . . . . . .78
Accepting Console Input . . . . . . . . . . . . . . . . . .80
You Do It . . . . . . . . . . . . . . . . . . . . . . . . .82
Declaring and Using Variables. . . . . . . . . . . . . . .82
Performing Arithmetic . . . . . . . . . . . . . . . . . .84
Working with Boolean Variables . . . . . . . . . . . . . .85
Using Escape Sequences . . . . . . . . . . . . . . . . .86
Writing a Program that Accepts User Input . . . . . . . . .87
Chapter Summary . . . . . . . . . . . . . . . . . . . . .88
Key Terms . . . . . . . . . . . . . . . . . . . . . . . .89
Review Questions . . . . . . . . . . . . . . . . . . . . .93
Exercises . . . . . . . . . . . . . . . . . . . . . . . . .97
CHAPTER 3 Using GUI Objects and the Visual
Studio IDE . . . . . . . . . . . . . . . 103
Creating a Form in the IDE . . . . . . . . . . . . . . . . 104
Using the Toolbox to Add a Button to a Form. . . . . . . 109
Adding Functionality to a Button on a Form. . . . . . . 111
Adding Labels and TextBoxes to a Form . . . . . . . . 114
Formatting Data in GUI Applications . . . . . . . . . . . 119
Naming Forms and Controls . . . . . . . . . . . . . . . 119
Correcting Errors . . . . . . . . . . . . . . . . . . . . 121
Deleting an Unwanted Event-Handling Method. . . . . . . 123
Failing to Close a Form Before Attempting
to Reexecute a Program . . . . . . . . . . . . . . . 124
Using Visual Studio Help . . . . . . . . . . . . . . . . 124
Deciding Which Interface to Use . . . . . . . . . . . . . 125
You Do It . . . . . . . . . . . . . . . . . . . . . . . . 127
Working With the Visual Studio IDE . . . . . . . . . . . 127
Providing Functionality for a Button . . . . . . . . . . 131
Adding a Second Button to a Form . . . . . . . . . . 132
Chapter Summary . . . . . . . . . . . . . . . . . . . . 133
Key Terms . . . . . . . . . . . . . . . . . . . . . . . 134
CONTENTS
vii
Review Questions . . . . . . . . . . . . . . . . . . . . 135
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 139
CHAPTER 4 Making Decisions . . . . . . . . . . . . 142
Understanding Logic-Planning Tools
and Decision Making . . . . . . . . . . . . . . . . . . 143
Making Decisions Using the if Statement . . . . . . . . . 146
A Note on Equivalency Comparisons . . . . . . . . . . . 152
Making Decisions Using the if-else Statement . . . . . . 152
Using Compound Expressions in if Statements . . . . . . 155
Using the Conditional AND Operator . . . . . . . . . . . 156
Using the Conditional OR Operator. . . . . . . . . . . . 157
Using the Logical AND and OR Operators. . . . . . . . . 158
Combining AND and OR Operators . . . . . . . . . . . . 159
Making Decisions Using the switch Statement . . . . . . 161
Using an Enumeration with a switch Statement . . . . . 165
Using the Conditional Operator . . . . . . . . . . . . . . 166
Using the NOT Operator . . . . . . . . . . . . . . . . . 167
Avoiding Common Errors When Making Decisions . . . . . . 169
Performing Accurate and Efficient Range Checks . . . . . 169
Using && and || Appropriately . . . . . . . . . . . . . 171
Using the ! Operator Correctly . . . . . . . . . . . . . 171
Decision-Making Issues in GUI Programs . . . . . . . . . . 173
You Do It . . . . . . . . . . . . . . . . . . . . . . . . 175
Using if-else Statements . . . . . . . . . . . . . . 175
Using AND and OR Logic . . . . . . . . . . . . . . . . 177
Chapter Summary . . . . . . . . . . . . . . . . . . . . 179
Key Terms . . . . . . . . . . . . . . . . . . . . . . . 181
Review Questions . . . . . . . . . . . . . . . . . . . . 183
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 188
CHAPTER 5 Looping . . . . . . . . . . . . . . . . 194
Using the while Loop . . . . . . . . . . . . . . . . . . 195
Using the for Loop . . . . . . . . . . . . . . . . . . . 201
Using the do Loop . . . . . . . . . . . . . . . . . . . . 204
Using Nested Loops . . . . . . . . . . . . . . . . . . . 207
Accumulating Totals . . . . . . . . . . . . . . . . . . . 210
Improving Loop Performance . . . . . . . . . . . . . . . 213
Looping Issues in GUI Programs. . . . . . . . . . . . . . 214
You Do It . . . . . . . . . . . . . . . . . . . . . . . . 217
Using a while Loop . . . . . . . . . . . . . . . . . . 217
Using for Loops . . . . . . . . . . . . . . . . . . . 218
viii
CONTENTS
Chapter Summary . . . . . . . . . . . . . . . . . . . . 221
Key Terms . . . . . . . . . . . . . . . . . . . . . . . 222
Review Questions . . . . . . . . . . . . . . . . . . . . 223
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 227
CHAPTER 6 Using Arrays . . . . . . . . . . . . . . 232
Declaring an Array and Assigning Values
to Array Elements . . . . . . . . . . . . . . . . . . . 233
Initializing an Array. . . . . . . . . . . . . . . . . . . 235
Accessing Array Elements . . . . . . . . . . . . . . . . 237
Using the Length Property. . . . . . . . . . . . . . . 237
Using foreach . . . . . . . . . . . . . . . . . . . . 238
Using foreach with Enumerations . . . . . . . . . . . 239
Searching an Array Using a Loop . . . . . . . . . . . . . 240
Using a for Loop to Search an Array . . . . . . . . . . 241
Using a while Loop to Search an Array . . . . . . . . . 243
Searching an Array for a Range Match . . . . . . . . . . 245
Using the BinarySearch(), Sort(),
and Reverse() Methods . . . . . . . . . . . . . . . 247
Using the BinarySearch() Method . . . . . . . . . . 247
Using the Sort() Method . . . . . . . . . . . . . . . 249
Using the Reverse() Method . . . . . . . . . . . . . 250
Using Multidimensional Arrays . . . . . . . . . . . . . . 252
Array Issues In GUI Programs . . . . . . . . . . . . . . . 257
You Do It . . . . . . . . . . . . . . . . . . . . . . . . 259
Creating and Using an Array . . . . . . . . . . . . . . 259
Using the Sort() and Reverse() Methods . . . . . . 260
Chapter Summary . . . . . . . . . . . . . . . . . . . . 261
Key Terms . . . . . . . . . . . . . . . . . . . . . . . 263
Review Questions . . . . . . . . . . . . . . . . . . . . 264
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 268
CHAPTER 7 Using Methods . . . . . . . . . . . . . 273
Understanding Methods and Implementation Hiding . . . . . 274
Understanding Implementation Hiding . . . . . . . . . . 275
Writing Methods with No Parameters
and No Return Value . . . . . . . . . . . . . . . . . . 276
Understanding Accessibility . . . . . . . . . . . . . . . 277
Understanding the Optional static Modifier. . . . . . . 278
Understanding the Return Type . . . . . . . . . . . . . 278
Understanding the Method Identifier . . . . . . . . . . . 279
Creating a Simple Method . . . . . . . . . . . . . . . 279
CONTENTS
ix
Writing Methods That Require a Single Argument . . . . . . 281
Writing Methods That Require Multiple Arguments. . . . . . 285
Writing a Method That Returns a Value . . . . . . . . . . . 287
Writing a Method that Returns a Boolean Value . . . . . . 289
Passing an Array to a Method. . . . . . . . . . . . . . . 290
Alternate Ways to Write a Main() Method Header . . . . . 295
Issues Using Methods in GUI Programs . . . . . . . . . . 297
Understanding Methods that are Automatically
Generated in the Visual Environment . . . . . . . . . . 297
Appreciating Scope in A GUI Program . . . . . . . . . . 298
Creating Methods to be Nonstatic when Associated
with a Form . . . . . . . . . . . . . . . . . . . . . 298
You Do It . . . . . . . . . . . . . . . . . . . . . . . . 299
Calling a Method . . . . . . . . . . . . . . . . . . . . 299
Writing a Method that Receives Parameters
and Returns a Value . . . . . . . . . . . . . . . . . 300
Chapter Summary . . . . . . . . . . . . . . . . . . . . 302
Key Terms . . . . . . . . . . . . . . . . . . . . . . . 303
Review Questions . . . . . . . . . . . . . . . . . . . . 305
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 309
CHAPTER 8 Advanced Method Concepts. . . . . . . . 315
Understanding Parameter Types. . . . . . . . . . . . . . 316
Using Mandatory Value Parameters . . . . . . . . . . . 316
Using Reference and Output Parameters . . . . . . . . . 318
Using Parameter Arrays . . . . . . . . . . . . . . . . 321
Overloading Methods. . . . . . . . . . . . . . . . . . . 323
Understanding Overload Resolution . . . . . . . . . . . 329
Understanding Built-In Overloaded Methods. . . . . . . . 330
Avoiding Ambiguous Methods . . . . . . . . . . . . . . . 332
Using Optional Parameters . . . . . . . . . . . . . . . . 334
Leaving Out Unnamed Arguments . . . . . . . . . . . . 336
Using Named Arguments . . . . . . . . . . . . . . . . 337
Overload Resolution with Named
and Optional Arguments. . . . . . . . . . . . . . . . 338
You Do It . . . . . . . . . . . . . . . . . . . . . . . . 339
Using Reference Parameters . . . . . . . . . . . . . . 339
Overloading Methods . . . . . . . . . . . . . . . . . . 341
Chapter Summary . . . . . . . . . . . . . . . . . . . . 342
Key Terms . . . . . . . . . . . . . . . . . . . . . . . 343
Review Questions . . . . . . . . . . . . . . . . . . . . 344
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 349
x
CONTENTS
CHAPTER 9 Using Classes and Objects . . . . . . . . 354
Understanding Class Concepts . . . . . . . . . . . . . . 355
Creating a Class from Which Objects Can Be
Instantiated . . . . . . . . . . . . . . . . . . . . . . 357
Creating Instance Variables and Methods. . . . . . . . . 358
Creating Objects. . . . . . . . . . . . . . . . . . . . . 361
Passing Objects to Methods . . . . . . . . . . . . . . 363
Creating Properties . . . . . . . . . . . . . . . . . . . 365
Using Auto-Implemented Properties . . . . . . . . . . . 369
More About public and private Access
Modifiers . . . . . . . . . . . . . . . . . . . . . . . 372
Understanding the this Reference . . . . . . . . . . . . 376
Understanding Constructors . . . . . . . . . . . . . . . 379
Passing Parameters to Constructors. . . . . . . . . . . 380
Overloading Constructors. . . . . . . . . . . . . . . . 381
Using Constructor Initializers . . . . . . . . . . . . . . 383
Using Object Initializers . . . . . . . . . . . . . . . . . 385
Overloading Operators . . . . . . . . . . . . . . . . . . 389
Declaring an Array of Objects. . . . . . . . . . . . . . . 394
Using the Sort() and BinarySearch() Methods
with Arrays of Objects . . . . . . . . . . . . . . . . 395
Understanding Destructors . . . . . . . . . . . . . . . . 399
Understanding GUI Application Objects . . . . . . . . . . 402
You Do It . . . . . . . . . . . . . . . . . . . . . . . . 404
Creating a Class and Objects . . . . . . . . . . . . . . 404
Using Auto-Implemented Properties . . . . . . . . . . . 407
Adding Overloaded Constructors To a Class . . . . . . . 407
Creating an Array of Objects . . . . . . . . . . . . . . 409
Chapter Summary . . . . . . . . . . . . . . . . . . . . 411
Key Terms . . . . . . . . . . . . . . . . . . . . . . . 413
Review Questions . . . . . . . . . . . . . . . . . . . . 416
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 420
CHAPTER 10 Introduction to Inheritance . . . . . . . . 427
Understanding Inheritance . . . . . . . . . . . . . . . . 428
Understanding Inheritance Terminology . . . . . . . . . 431
Extending Classes . . . . . . . . . . . . . . . . . . . . 433
Using the protected Access Specifier . . . . . . . . . . 435
Overriding Base Class Methods . . . . . . . . . . . . . . 440
Accessing Base Class Methods from a Derived Class . . . 443
Understanding How a Derived Class Object “is an”
Instance of the Base Class . . . . . . . . . . . . . . . 445
Using the Object Class . . . . . . . . . . . . . . . . . 447
Using the Object Class’s GetType() Method . . . . . 449
CONTENTS
xi
Using the Object Class’s ToString() Method . . . . . . 449
Using the Object Class’s Equals() Method . . . . . . 450
Using the Object Class’s GetHashCode() Method . . . 451
Working with Base Class Constructors. . . . . . . . . . . 453
Using Base Class Constructors That Require Arguments . . 454
Creating and Using Abstract Classes . . . . . . . . . . . 456
Creating and Using Interfaces. . . . . . . . . . . . . . . 460
Using Extension Methods . . . . . . . . . . . . . . . . . 464
Recognizing Inheritance in GUI Applications
and Recapping the Benefits of Inheritance . . . . . . . . 467
You Do It . . . . . . . . . . . . . . . . . . . . . . . . 469
Extending a Class . . . . . . . . . . . . . . . . . . . 471
Using Base Class Members in a Derived Class . . . . . . 472
Adding Constructors to Base and Derived Classes . . . . 475
Chapter Summary . . . . . . . . . . . . . . . . . . . . 476
Key Terms . . . . . . . . . . . . . . . . . . . . . . . 477
Review Questions . . . . . . . . . . . . . . . . . . . . 479
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 483
CHAPTER 11 Exception Handling . . . . . . . . . . . 490
Understanding Exceptions . . . . . . . . . . . . . . . . 491
Purposely Generating a SystemException . . . 493
Understanding Traditional and Object-Oriented
Error-Handling Methods . . . . . . . . . . . . . . . . . 495
Understanding Object-Oriented Exception-Handling
Methods. . . . . . . . . . . . . . . . . . . . . . . 496
Using the Exception Class’s ToString()Method
and Message Property . . . . . . . . . . . . . . . . . 499
Catching Multiple Exceptions . . . . . . . . . . . . . . 502
Using the finally Block . . . . . . . . . . . . . . . . 507
Handling Exceptions Thrown from Outside
Methods. . . . . . . . . . . . . . . . . . . . . . . . 509
Tracing Exceptions Through the Call Stack . . . . . . . 513
A Case Study: Using StackTrace . . . . . . . . . . . 514
Creating Your Own Exception Classes . . . . . . . . . . 518
Rethrowing an Exception. . . . . . . . . . . . . . . . 522
You Do It . . . . . . . . . . . . . . . . . . . . . . . . 524
Purposely Causing Exceptions . . . . . . . . . . . . 524
Handling Exceptions . . . . . . . . . . . . . . . . . 526
Catching Various Exception Types. . . . . . . . . . . 527
Chapter Summary . . . . . . . . . . . . . . . . . . . . 529
Key Terms . . . . . . . . . . . . . . . . . . . . . . . 530
Review Questions . . . . . . . . . . . . . . . . . . . . 531
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 536
xii
CONTENTS
CHAPTER 12 Using Controls . . . . . . . . . . . . . 540
Understanding Controls . . . . . . . . . . . . . . . . 541
Examining the IDE’s Automatically Generated Code . . . . . 545
Setting a Control’s Font. . . . . . . . . . . . . . . . 549
Using a LinkLabel . . . . . . . . . . . . . . . . . . . 551
Adding Color to a Form . . . . . . . . . . . . . . . . . 555
Using CheckBox and RadioButton Objects . . . . . . . 557
Adding a PictureBox to a Form . . . . . . . . . . . . 561
Adding ListBox, CheckedListBox, and ComboBox
Controls to a Form . . . . . . . . . . . . . . . . . 564
Adding MonthCalendar and DateTimePicker
Controls to a Form . . . . . . . . . . . . . . . . . 569
Working with a Form’s Layout . . . . . . . . . . . . . . 573
Understanding GroupBoxes and Panels . . . . . . . . 576
Adding a MenuStrip to a Form . . . . . . . . . . . . . 577
Using Other Controls . . . . . . . . . . . . . . . . . 580
You Do It . . . . . . . . . . . . . . . . . . . . . . . . 580
Adding Labels to a Form and Changing their
Properties . . . . . . . . . . . . . . . . . . . . . . 580
Examining the Code Generated by the IDE . . . . . . . . 583
Adding CheckBoxes to a Form. . . . . . . . . . . . . 586
Adding RadioButtons to a Form . . . . . . . . . . . 592
Chapter Summary . . . . . . . . . . . . . . . . . . . . 595
Key Terms . . . . . . . . . . . . . . . . . . . . . . . 597
Review Questions . . . . . . . . . . . . . . . . . . . . 598
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 602
CHAPTER 13 Handling Events . . . . . . . . . . . . . 606
Event Handling . . . . . . . . . . . . . . . . . . . . . 607
Understanding Delegates . . . . . . . . . . . . . . . . . 611
Creating Composed Delegates . . . . . . . . . . . . . 613
Declaring Your Own Events and Handlers and Using
the Built-in EventHandler. . . . . . . . . . . . . . . 615
Using the Built-in EventHandler . . . . . . . . . . . . 619
Handling Control Component Events. . . . . . . . . . . 621
Handling Mouse and Keyboard Events . . . . . . . . . . . 626
Handling Mouse Events . . . . . . . . . . . . . . . . . 626
Handling Keyboard Events . . . . . . . . . . . . . . . 628
Managing Multiple Controls. . . . . . . . . . . . . . . 631
Defining Focus. . . . . . . . . . . . . . . . . . . . . 631
Handling Multiple Events with a Single Handler . . . . . . 632
Continuing to Learn about Controls and Events. . . . . . 635
CONTENTS
xiii
You Do It . . . . . . . . . . . . . . . . . . . . . . . . 635
Creating Delegates. . . . . . . . . . . . . . . . . . . 635
Creating a Composed Delegate . . . . . . . . . . . . . 637
Creating a Delegate that Encapsulates Instance
Methods. . . . . . . . . . . . . . . . . . . . . . . 640
Creating an Event Listener . . . . . . . . . . . . . . . 642
Using TabIndex . . . . . . . . . . . . . . . . . . . 644
Associating One Method with Multiple Events . . . . . . . 645
Chapter Summary . . . . . . . . . . . . . . . . . . . . 646
Key Terms . . . . . . . . . . . . . . . . . . . . . . . 648
Review Questions . . . . . . . . . . . . . . . . . . . . 648
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 653
CHAPTER 14 Files and Streams . . . . . . . . . . . . 656
Computer Files and the File and Directory
Classes . . . . . . . . . . . . . . . . . . . . . . . . 657
Using the File and Directory Classes . . . . . . . . . 658
Understanding Data Organization Within a File . . . . . . . 662
Understanding Streams . . . . . . . . . . . . . . . . . 665
Writing to and Reading From a Sequential Access
Text File. . . . . . . . . . . . . . . . . . . . . . . . 669
Writing Data to a Sequential Access Text File . . . . . . . 669
Reading from a Sequential Access Text File . . . . . . . 672
Searching a Sequential Text File. . . . . . . . . . . . . . 675
Understanding Serialization and Deserialization. . . . . . . 678
You Do It . . . . . . . . . . . . . . . . . . . . . . . . 682
Creating a File. . . . . . . . . . . . . . . . . . . . . 682
Reading from a File . . . . . . . . . . . . . . . . . . 684
Using the Seek() Method . . . . . . . . . . . . . . . 685
Creating a Text File in a GUI Environment. . . . . . . . . 687
Reading Data from a Text File into a Form . . . . . . . . 691
Chapter Summary . . . . . . . . . . . . . . . . . . . . 696
Key Terms . . . . . . . . . . . . . . . . . . . . . . . 698
Review Questions . . . . . . . . . . . . . . . . . . . . 700
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 704
CHAPTER 15 Using LINQ to Access Data
in C# Programs . . . . . . . . . . . . . 708
Understanding Relational Database Fundamentals. . . . . . 709
Creating Databases and Table Descriptions . . . . . . . . 712
Identifying Primary Keys . . . . . . . . . . . . . . . . 714
Understanding Database Structure Notation . . . . . . . 715
xiv
CONTENTS
Creating SQL Queries . . . . . . . . . . . . . . . . . . 716
Creating an Access Database . . . . . . . . . . . . . . . 718
Understanding Implicitly Typed Variables . . . . . . . . . . 721
Understanding LINQ . . . . . . . . . . . . . . . . . . . 723
Retrieving Data from an Access Database in C# . . . . . . 727
Using LINQ Queries with an Access Database Table . . . . . 731
Using LINQ Operators to Sort and Group Data . . . . . . . 736
You Do It . . . . . . . . . . . . . . . . . . . . . . . . 740
Adding a Dataset to a Project . . . . . . . . . . . . . . 740
Querying a Dataset. . . . . . . . . . . . . . . . . . . 743
Allowing the User to Provide Selection Criteria . . . . . . 744
Grouping Data . . . . . . . . . . . . . . . . . . . . . 747
Chapter Summary . . . . . . . . . . . . . . . . . . . . 750
Key Terms . . . . . . . . . . . . . . . . . . . . . . . 752
Review Questions . . . . . . . . . . . . . . . . . . . . 754
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 758
APPENDIX A Operator Precedence And Associativity. . . 764
APPENDIX B Understanding Numbering Systems
and Computer Codes. . . . . . . . . . . 766
APPENDIX C Using The IDE Editor. . . . . . . . . . . 775
Glossary . . . . . . . . . . . . . . . . 779
Index . . . . . . . . . . . . . . . . . 799
Preface
Microsoft Visual C# 2010, Fourth edition provides the beginning
programmer with a guide to developing programs in C#. C# is a
language developed by the Microsoft Corporation as part of the
.NET Framework and Visual Studio platform. e .NET Framework
contains a wealth of libraries for developing applications for the
Windows family of operating systems. With C#, you can build small,
reusable components that are well-suited to Web-based program-
ming applications. Although similar to Java and C++, many features
of C# make it easier to learn and ideal for the beginning programmer.
You can program in C# using a simple text editor and the command
prompt, or you can manipulate program components using Visual
Studio’s sophisticated Integrated Development Environment. is
book provides you with the tools to use both techniques.
is textbook assumes that you have little or no programming
experience. e writing is nontechnical and emphasizes good pro-
gramming practices. e examples are business examples; they do
not assume mathematical background beyond high school business
math. Additionally, the examples illustrate one or two major points;
they do not contain so many features that you become lost following
irrelevant and extraneous details. is book provides you with a solid
background in good object-oriented programming techniques and
introduces you to object-oriented terminology using clear, familiar
language.
Organization and Coverage
Microsoft Visual C# 2010 presents C# programming concepts,
enforcing good style, logical thinking, and the object-oriented
paradigm. Chapter 1 introduces you to the language by letting you
create working C# programs using both the simple command line and
the Visual Studio environment. In Chapter 2 you learn about data and
how to input, store, and output data in C#. Chapter 3 provides a quick
start to creating GUI applications. You can take two approaches:
You can cover Chapter 3 and learn about GUI objects so that you •
can create more visually interesting applications in the subsequent
xv
xvi
PREFACE
chapters on decision making, looping, and array manipulation.
ese subsequent chapters confi ne GUI examples to the end of the
chapters, so you can postpone GUI manipulation if you want.
You can skip Chapter 3 until learning the fundamentals of decision •
making, looping, and array manipulation, and until studying
object-oriented concepts such as classes, objects, polymorphism,
inheritance, and exception handling. en, after Chapter 11, you
can return to Chapter 3 and use the built-in GUI component
classes with a deeper understanding of how they work.
In Chapters 4, 5, and 6, you learn about the classic programming
structures—making decisions, looping, and manipulating arrays—and
how to implement them in C#. Chapters 7 and 8 provide a thorough
study of methods, including passing parameters into and out of
methods and overloading them.
Chapter 9 introduces the object-oriented concepts of classes,
objects, data hiding, constructors, and destructors. After completing
Chapters 10 and 11, you will be thoroughly grounded in the object-
oriented concepts of inheritance and exception handling, and will
be able to take advantage of both features in your C# programs.
Chapter 12 continues the discussion of GUI objects from Chapter 3.
You will learn about controls, how to set their properties, and how
to make attractive, useful, graphical, and interactive programs.
Chapter 13 takes you further into the intricacies of handling events
in your interactive GUI programs. In Chapter 14, you learn to save
data to and retrieve data from fi les. In Chapter 15 you learn how to
interact with databases in C# programs—an increasingly valuable
skill in the information-driven business world. C# supports LINQ
(Language INtegrated Query) statements, which allow you to
integrate SQL-like queries into C# programs; Chapter 15 provides
you with the fundamentals of this important technology.
New to this Edition!
Microsoft Visual C# 2010 is a superior textbook because it also
includes the following new features:
C# 4.0 IN VISUAL STUDIO 2010 is edition is written and tested
using the latest edition of C#.
VIDEO LESSONS Each chapter includes three or more video les-
sons produced by the author. ese short videos provide instruc-
tion, further explanation, or background about a topic covered in the
corresponding chapter. ese videos are especially useful for online
classes, for student review before exams, and for students who are
audio learners.
PREFACE
xvii
EARLY GUI APPLICATIONS Students now can begin to cre-
ate GUI applications in Chapter 3. e earlier introduction helps
engage students who have used GUI applications their entire lives.
In subsequent chapters on selections, loops, arrays, and methods,
students apply concepts to applications in both console and GUI
environments. is keeps some examples simple while increasing the
understanding that input, processing, and output are programming
universals no matter what interface is used. e book is structured
so that students who want to skip Chapter 3 until they understand
object-oriented programming can do so with no loss of continuity.
EXPANDED COVERAGE OF METHODS Instructions for using
methods have been expanded and divided into two chapters. e
introductory method chapter covers the basics of calling methods,
passing arguments, and returning values. e advanced chapter dis-
cusses reference parameters, output parameters, optional parameters,
parameter arrays, overloading methods, and avoiding ambiguity.
(Optional parameters are a new feature in C# 4.0.)
MORE ENGAGING EXERCISES ON SPECIFIC TOPICS Many
chapters have additional exercises that employ string manipulation and
enumerations. Gaming exercises have been added to many chapters.
Features of the Text
Microsoft Visual C# 2010 also includes the following features:
OBJECTIVES Each chapter begins with a list of objectives so you
know the topics that will be presented in the chapter. In addition to
providing a quick reference to topics covered, this feature off ers a use-
ful study aid.
NOTES ese tips provide additional information—for
example, an alternative method of performing a procedure,
another term for a concept, background information on a
technique, or a common error to avoid.
FIGURES Each chapter contains many fi gures. Code fi gures are
most frequently 25 lines or shorter, illustrating one concept at a time.
Frequently placed screen shots show exactly how program output
appears. In this edition, all C# keywords that appear in fi gures are
bold to help them stand out from programmer-created identifi ers.
SUMMARIES Following each chapter is a summary that recaps the
programming concepts and techniques covered in the chapter. is
feature helps you to recap and check your understanding of the main
points in each chapter.
xviii
PREFACE
KEY TERMS Each chapter includes a list of newly introduced vocab-
ulary, shown in the order of appearance in the text. e list of key
terms provides a review of the major concepts in the chapter.
YOU DO IT In each chapter, step-by-step exercises help the student
create multiple working programs that emphasize the logic a pro-
grammer uses in choosing statements. is section enables students
to achieve success on their own—even students in online or distance
learning classes.
TWO TRUTHS AND A LIE is short quiz appears after each main
chapter section, with answers provided. is quiz contains three
statements—two true and one false—and the student must identify
the false one. Over the years, students have requested answers to
problems, but we have hesitated to distribute them in case instructors
want to use problems as assignments or test questions. ese quizzes
provide students with immediate feedback as they read, without “giv-
ing away” answers to the existing multiple-choice and programming
problem questions.
REVIEW QUESTIONS Each chapter contains 20 multiple-choice
review questions that provide a review of the key concepts in the chapter.
EXERCISES Each chapter concludes with meaningful programming
exercises that provide additional practice of the skills and concepts
you learned in the chapter. ese exercises increase in diffi culty and
allow you to explore logical programming concepts.
DEBUGGING EXERCISES Each chapter contains four pro-
grams that have syntax and/or logical errors for you to fi x.
Completing these exercises provides valuable experience in
locating errors, interpreting code written by others, and observ-
ing how another programmer has approached a problem.
UP FOR DISCUSSION Each chapter concludes with a few
thought-provoking questions that concern programming in
general or C# in particular. e questions can be used to
start classroom or online discussions, or to develop and
encourage research, writing, and language skills.
PROGRAM CODE e downloadable student fi les provide code for
each full program presented in the chapter fi gures. Providing the code
on disk allows students to run it, view the results for themselves, and
experiment with multiple input values. Having the code on disk also
enables students to experiment with the code without a lot of typing.
GLOSSARY A glossary contains defi nitions for all key terms in the
book, presented in alphabetical order.
PREFACE
xix
QUALITY Every program example in the book, as well as every exer-
cise, case project, and game solution, was tested by the author and
again by a Quality Assurance team using Visual Studio 2010.
Instructor Resources
e following supplemental materials are available when this book is
used in a classroom setting. All of the teaching tools for this book are
provided to the instructor on a single CD-ROM, and are also avail-
able for download at the companion site for the text (www.cengage.
com/coursetechnology).
ELECTRONIC INSTRUCTOR’S MANUAL e Instructor’s Manual
that accompanies this textbook includes:
Additional instructional material to assist in class preparation, •
including suggestions for lecture topics.
Solutions to Review Questions, end-of-chapter programming exer- •
cises, debugging exercises, and Up For Discussion questions.
EXAMVIEW
®
is textbook is accompanied by ExamView, a powerful
testing software package that allows instructors to create and admin-
ister printed, computer (LAN-based), and Internet exams. ExamView
includes hundreds of questions that correspond to the topics covered
in this text, enabling students to generate detailed study guides that
include page references for further review. e computer-based and
Internet testing components allow students to take exams at their com-
puters, and save the instructor time by grading each exam automatically.
POWERPOINT PRESENTATIONS is book comes with Microsoft
PowerPoint slides for each chapter. ese slides are included as a
teaching aid for classroom presentation; teachers can make them
available on the network for chapter review or print them for class-
room distribution. Instructors can add their own slides for additional
topics they introduce to the class.
SOLUTION FILES Solutions to all “You Do It” exercises and end-of
chapter exercises are provided on the Instructor Resources CD-ROM
and on the Course Technology Web site at www.cengage.com/
coursetechnology. e solutions are password protected.
DISTANCE LEARNING Cengage Learning is proud to present online
test banks in WebCT and Blackboard to provide the most complete
and dynamic learning experience possible. Instructors are encouraged
to make the most of the course, both online and offl ine. For more
information on how to access the online test bank, contact your local
Course Technology sales representative.
xx
PREFACE
Acknowledgments
I would like to thank all of the people who helped to make this book
a reality, especially Dan Seiter, the development editor, who once
again worked against multiple, aggressive deadlines to make this
book into a superior instructional tool. anks also to Alyssa Pratt,
Senior Product Manager; Amy Jollymore, Acquisitions Editor; and
Lisa Weidenfeld, Content Project Manager. I am grateful to be able to
work with so many fi ne people who are dedicated to producing good
instructional materials.
I am also grateful to the many reviewers who provided helpful
comments and encouragement during this book’s development,
including Matthew Butcher, Mohave Community College;
Dan Guilmette, Cochise College; and Jorge Vallejos, Columbus
State Community College.
anks, too, to my husband, Geoff , for his constant support and
encouragement. Finally, this book is dedicated to Andrea and Forrest,
wishing them a lifetime of happiness together.
Joyce Farrell
Read This
Before You
Begin
To the User
To complete the debugging exercises in this book, you will need data
fi les that have been created specifi cally for the book. Your instructor
will provide the data fi les to you. You also can obtain the fi les
electronically from the Course Technology Web site by connecting to
www.cengage.com/coursetechnology and then searching for this book
title. Note that you can use a computer in your school lab or your
own computer to complete the exercises in this book.
e data fi les for this book are organized such that the examples and
exercises are divided into folders named Chapter.xx, where xx is the
chapter number. You can save these fi les in the same folders unless
specifi cally instructed to do otherwise in the chapter.
Using Your Own Computer
To use your own computer to complete the steps and exercises, you
will need the following:
SOFTWARE Microsoft Visual C# 2010, including the Microsoft.NET
Framework. If your book came with a copy of the software, you may
install it on your computer and use it to complete the material.
HARDWARE Minimum requirements identifi ed by Microsoft are a
1.6 GHz CPU, 1024 MB of RAM, 3 GB of available hard disk space,
5400 RPM hard disk drive, DirectX 9-capable video card that runs at
1280×1024 or higher display resolution, and a DVD-ROM drive.
OPERATING SYSTEM Windows 7, Vista, or XP.
xxi
DATA FILES You will not be able to complete the debugging exer-
cises in this book using your own computer unless you have the data
fi les. You can get the data fi les from your instructor, or you can obtain
them electronically from the Course Technology Web site by con-
necting to www.cengage.com/coursetechnology and searching for this
book title. Additionally, the data fi les include code for every example
shown in a fi gure in the book.
To the Instructor
To complete the debugging exercises and chapters in this book, your
users must work with a set of data fi les. ese fi les are included on
the Instructor Resources CD. You can also obtain these fi les electron-
ically through the Course Technology Web site at www.cengage.com/
coursetechnology. Follow the instructions in the Help fi le to copy the
user fi les to your server or stand-alone computer. You can view the
Help fi le using a text editor such as WordPad or Notepad.
Once the fi les are copied, you can make copies for the users yourself
or tell them where to fi nd the fi les so they can make their own copies.
License to Use Data Files
You are granted a license to copy the fi les that accompany this book
to any computer or computer network used by people who have
purchased this book.
xxii
BEFORE YOU BEGIN
CHAPTER 1
A First Program
Using C#
In this chapter you will:
Learn about programming
Learn about procedural and object-oriented programming
Learn about the features of object-oriented programming
languages
Learn about the C# programming language
Write a C# program that produces output
Learn how to select identifi ers to use within your programs
Improve programs by adding comments and using the
System namespace
Write and compile a C# program using the command
prompt and using Visual Studio