WHAT YOU NEED TO USE THIS BOOK All the examples in this book were written using Visual Studio 2012 and C#.. Although Visual Studio Professional has a limited trial period, that time slic
Trang 3INTRODUCTION xxv
PART I GETTING STARTED CHAPTER 1 Introducing C# 3
CHAPTER 2 Understanding Objects 19
PART II UNDERSTANDING C# SYNTAX CHAPTER 3 Understanding Data Types 59
CHAPTER 4 Understanding C# Statements 81
CHAPTER 5 Understanding Reference Data Types 109
CHAPTER 6 Making Decisions in Code 147
CHAPTER 7 Statement Repetition Using Loops 169
CHAPTER 8 Understanding Arrays and Collections 193
PART III WRITING YOUR OWN CLASSES CHAPTER 9 Designing Classes 227
CHAPTER 10 Designing and Writing Custom Classes 255
CHAPTER 11 Exception Handling and Debugging 295
CHAPTER 12 Generics 327
PART IV STORING DATA CHAPTER 13 Using Disk Data Files 359
CHAPTER 14 Using Databases 425
CHAPTER 15 Using LINQ 459
Continues
Trang 4CHAPTER 18 Web Programming 523
APPENDIX Answers to Exercises 539
INDEX 577
Trang 5with C#
Trang 7with C#
Jack Purdum
Trang 8Indianapolis, IN 46256
www.wiley.com
Copyright © 2013 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108
of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers,
MA 01923, (978) 750-8400, fax (978) 646-8600 Requests to the Publisher for permission should be addressed to the
Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 6011, fax (201)
748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with
respect to the accuracy or completeness of the contents of this work and specifi cally disclaim all warranties, including
without limitation warranties of fi tness for a particular purpose No warranty may be created or extended by sales or
pro-motional materials The advice and strategies contained herein may not be suitable for every situation This work is sold
with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services
If professional assistance is required, the services of a competent professional person should be sought Neither the
pub-lisher nor the author shall be liable for damages arising herefrom The fact that an organization or Web site is referred to
in this work as a citation and/or a potential source of further information does not mean that the author or the publisher
endorses the information the organization or Web site may provide or recommendations it may make Further, readers
should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was
written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the
United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand Some material included with
standard print versions of this book may not be included in e-books or in print-on-demand If this book refers to media
such as a CD or DVD that is not included in the version you purchased, you may download this material at
http://booksupport.wiley.com For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2012948651
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are
trade-marks or registered tradetrade-marks of John Wiley & Sons, Inc and/or its affi liates, in the United States and other countries,
and may not be used without written permission All other trademarks are the property of their respective owners John
Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.
Trang 11DR JACK PURDUM started his programming career on an IBM 360 mainframe
as a graduate student in the 1960s In the mid-1970s, he became interested
in software development for microcomputers, and he founded his own ware development company (Ecosoft, Inc.) in 1977 The company’s main product was a statistics package (Microstat) that he wanted to rewrite in a new language called C Lacking a suitable C compiler, Dr Purdum’s company developed its own MS-DOS-based C compiler and other programming tools
soft-He has been involved with language instruction ever since Dr Purdum has authored 17 texts and numerous programming articles and has received several teaching awards He retired from Purdue University’s College of Technology and is currently involved with on-site train-ing and embedded systems programming
Trang 13Mary Beth Wakefi eld
Freelancer Editorial Manager
Trang 15NO BOOK IS WRITTEN without massive effort by others Tom Dinse and the editorial staff at Wrox have all made this a better book.
A large group of people also contributed to this book in a variety of different ways, providing thing from encouragement to ideas for examples First, thanks to my students who served as guinea pigs for virtually everything used in this text Others who contributed include Jerry and Barb Forro, Bill Gromer, Joe Kack, Katie Mohr, John Purdum, and John Strack A special vote of appreciation
every-to Jane Holcer for her unwavering support and encouragement throughout the process of writing this book
Trang 17Creating a Simple Application Using Objects 40
Using the Program Steps to Create a Program Plan 40
Trang 182: Input 41
Critique of the btnDisplayOutput Click Event Code 53
Summary 54
PART II: UNDERSTANDING C# SYNTAX
Which Floating-Point Data Type Should You Use? 74
Using IntelliSense to Locate Program Errors 76
Summary 79
Basic Building Blocks of a Programming Language 82
Expressions 83Statements 83
Defi ning a Variable from the Compiler’s Point of View 87
Trang 19Write Your Code So That Someone Else Can Easily Understand It 101
Summary 106CHAPTER 5: UNDERSTANDING REFERENCE DATA TYPES 109
Why Reference Types Are Diff erent from Value Types 113
Reference Type Variables Versus Value Type Variables 115Why Do Reference Variables Work the Way They Do? 115
Letting IntelliSense Show You Properties and Methods 119
An Important Distinction Between Properties and Methods 120
Trang 20Strings and Escape Sequences 131
Using Relational Operators—The if Statement 148
Shorthand for Simple if-else: The Ternary Operator 154Style Considerations for if and if-else Statements 155
The Three Conditions of a Well-Behaved Loop 170
Trang 21Summary 190CHAPTER 8: UNDERSTANDING ARRAYS AND COLLECTIONS 193
Casts 201
Which Array Defi nition/Initialization Syntax Is Best? 212
PART III: WRITING YOUR OWN CLASSES
Trang 22Display Step 238
Design Intent and Access Specifi ers for Methods 242
Summary 252CHAPTER 10: DESIGNING AND WRITING CUSTOM CLASSES 255Constructors 256
How Does Visual Studio Know Whether to
What to Do if an Error Occurs in a Property Method 264
Cohesion 266Coupling 266
UML Class Diagram for Shuffl e Deck Program 268
Trang 23Class Properties, Constructor, and Property Methods 275
Designing a Card Game Using clsCardDeck 278
Summary 291CHAPTER 11: EXCEPTION HANDLING AND DEBUGGING 295
Detection 314Isolation 316
Trang 24PART IV: STORING DATA
Advantages and Disadvantages of Sequential Files 380
Advantages and Disadvantages of Random Access Files 383
Summary 422
Trang 25Aggregates 437
Displaying Database Data Without Data Binding 451
PART V: ADVANCED TOPICS
Polymorphism 492
Summary 498
Trang 26Using a Printer 501 Threading 509
Summary 535
INDEX 577
Trang 27OVER THE PAST 30 YEARS I’VE WRITTEN 18 BOOKS on various programming topics You might der, why so many…? Didn’t I get it right the fi rst time? Well, no, I didn’t…not really When I wrote
won-my fi rst book more than 30 years ago, object-oriented programming (OOP) was obscure at best and unknown to most Like so many others, I had to go through the OOP learning process before
I could appreciate what OOP was all about I have a feeling that there are a lot of people out there who still feel that way
Each time I teach a programming class, I learn new and better ways to explain things When I look out across a classroom fi lled with students and it looks like a still-life painting, it’s time to back off, retool, and try a different approach to whatever concept it is I’m trying to teach Every class I’ve taught has offered new perspectives on how I teach and how students learn I’ve had the opportunity
to teach both in a university setting and on site at various companies both here and in Europe Each experience presented different teaching challenges Changing my examples and the techniques I use
to teach programming concepts is one of the reasons I came back to teaching after so many years away… I missed the learning experience
A number of the books I wrote were concerned with languages other than C#, but that too provides for an enriching experience for me as an instructor The strengths and weaknesses of a language can
be appreciated only if you’ve grappled with some other less-than-perfect languages The fact that programming languages continue to evolve supports the conclusion that I’m not the only one who
is still learning After all this time, the one thing that I have learned with absolute certainty is that whatever I know today will likely be out of date tomorrow
Perhaps the question you should ask yourself is, “Why should I buy this book instead of someone else’s book?” A number of factors come into play, but only one actually makes a difference: This book provides the techniques, examples, and approach to teaching the various programming con-cepts I’ve honed through working with literally thousands of students I’ve learned what works and what doesn’t So many authors today are, no doubt, brilliant coders, but they haven’t had to stumble through the bad examples and teaching methods that simply don’t work Writing good code does not necessarily equate to writing good books
I think you will fi nd this book informative, clear in its examples, and perhaps even entertaining in its narrative I hope you’ll give it a chance… I think you’ll enjoy the book Even more important, however, is that you will come to appreciate all that object-oriented programming and C# can do for you
Trang 28WHO THIS BOOK IS FOR
The book assumes no prior programming experience That does not mean, however, that the book
is “dumbed down” in any way I build slowly, placing you on solid ground before the next topic is
introduced I encourage you to write your own programs and do the exercises at the end of each
chapter If you try to take shortcuts, you’re actually shortchanging yourself You should type in
every line of code in this book and experiment with it Do so and you will pick up the language
twice as fast and with greater understanding than if you don’t do the examples (You can download
the code from the Wrox website Details are provided later.) You can learn programming only by
writing programs and I encourage you to do so at every possible opportunity
If you have some programming experience, that’s fi ne, too This book will likely be an easy read for
you However, you will learn some things along the way If you have never programmed before…
perfect! You don’t have the bad programming baggage so many bring to the experience when they
learn a new language
This is the perfect book for someone who knows a programming language but learned that
lan-guage before object-oriented programming techniques came into existence There are a lot of
“old-timers” like myself who would like to retrain themselves in OOP techniques and gain a full
appreciation of what OOP brings to the table This book suits that need perfectly
Unlike other books, I don’t recommend skipping chapters if you already know a programming
language or have some other prior programming experience If you’re familiar with symbol tables,
lvalues, and rvalues, and the Bucket Analogy, good—but it won’t hurt you to read about them again
from a different perspective No shortcuts, remember
WHAT THIS BOOK COVERS
This text begins with a nonprogramming-language introduction to object-oriented programming
The goal of that chapter is to present the concept of objects fi rst and then ease into how objects
may be viewed in C# Virtually all of the concepts presented in this book are portable to other
lan-guages The program design skills, coding style and techniques, and debugging methods are
applica-ble to almost any programming language C# and Visual Studio are simply the vehicle for teaching
these skills
Throughout the book common, easily understood examples introduce new programming concepts
Most of the C# programming language is covered; although, there are a few less-common topics not
covered These omissions aren’t important to the task at hand, which is to teach you OOP using C#
When you have completed this book, you should feel comfortable designing, writing, testing, and
debugging complex OOP programs of your own design
Trang 29HOW THIS BOOK IS STRUCTURED
The sequencing of the chapters was dictated by what I use when I taught this class to freshmen dents The chapter count is no accident and is geared to a college programming course of one semes-ter in length If you use the book as a self-study guide, great, but don’t feel that you need to speed through the book Understand each chapter before moving onto the next Take the time to let things
stu-“sink in.”
The sequence makes logical sense, and each chapter builds upon the information contained in the previous chapters Although you could skip around, this would detract from the learning experi-ence I have my own way to explain things and some are unusual…but they work
Each chapter has several questions and exercises at the end of it You are encouraged to work through those examples before you progress to the next chapter As said previously, you can learn programming only by writing programs It’s easy to get lulled into a false sense of security by read-ing code and saying, “Yeah, I got that.” Perhaps…perhaps not Writing your own programs is the
only way to know for sure.
WHAT YOU NEED TO USE THIS BOOK
All the examples in this book were written using Visual Studio 2012 and C# As I write this rial, C# Express is available only for Windows 8 However, Visual Studio Professional is available for other versions of Windows Although Visual Studio Professional has a limited trial period, that time slice is more than long enough to work through this book By the time you fi nish this book, you will likely want to purchase Visual Studio, anyway
mate-Instructions in Chapter 1, “Introducing C#,” tell you how to download and install Visual Studio Professional and C# from Microsoft at no charge If you use Windows 8, you may want to download the Express version of Visual Studio It is an incredible piece of software and has most
of the functionality of the full Visual Studio There are some nice tools missing from the Express edition, but there is enough there for you to experience most of what Visual Studio and C# have
to offer
You should use a Pentium-based system (although emulators also exist for the Mac and Linux, and they appear to work well) with at least 4G of memory and 11G of disk space As mentioned, the version of Windows you use may affect which fl avor of Visual Studio you want to download
The examples in this book work with either the Professional or Express versions of C# After those requirements, the system you use is a matter of taste
The source code for the samples is available for download from the Wrox website at:
www.wrox.com/remtitle.cgi?isbn=1118336925
Trang 30To help you get the most from the text and keep track of what’s happening, this book uses a
num-ber of style conventions throughout the book What follows is a list of the book’s style conventions
(You will also see a number of programming conventions, which are introduced as needed
through-out the text.)
TRY IT OUT
The Try it Out is an exercise you should work through, following the text in the book
1. They usually consist of a set of steps
2. Each step has a number
3. Follow the steps through with your copy of the code
How it Works
After each Try It Out, the code you’ve typed will be explained in detail.
NOTE Notes, tips, hints, tricks, and asides to the current discussion are off set
and placed in italics like this
As for styles in the text:
‰ We italicize new terms and important words when we introduce them.
‰ We show keyboard strokes like this: Ctrl+A
‰ We show fi lenames, URLs, and code within the text like so: persistence.properties
Code snippets and listings are presented in this way:
We use a monofont type with no highlighting for most code examples.
Code snippets and listings are almost always more than one line long.
SOURCE CODE
As you work through the examples in this book, you may choose either to type in all the code
man-ually or to use the source code fi les that accompany the book All the source code used in this book
is available for download at www.wrox.com
You can also search for the book at www.wrox.com by ISBN (the ISBN for this book is
978-1-118-33692-2 to fi nd the code And a complete list of code downloads for all current Wrox
books is available at www.wrox.com/dynamic/books/download.aspx
Trang 31At the beginning of each chapter, we’ve provided the folder name for the code in the chapter
Throughout each chapter, you can also fi nd references to the names of the individual code fi les as needed in listing titles and text
Most of the code on www.wrox.com is compressed in ZIP, RAR, or a similar archive format priate to the platform After you download the code, just decompress it with an appropriate com-pression tool
appro-ERRATA
We make every effort to ensure that there are no errors in the text or in the code However, no one is perfect, and mistakes do occur If you fi nd an error in one of our books, like a spelling mistake or faulty piece of code, we would be grateful for your feedback By sending in errata you may save another reader hours of frustration, and at the same time you can help us provide even higher-quality information
To fi nd the errata page for this book, go to:
www.wrox.com/remtitle.cgi?isbn=1118336925
and click the Errata link On this page you can view all errata that has been submitted for this book and posted by Wrox editors
If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/
techsupport.shtml and complete the form there to send us the error you have found We’ll check the information and, if appropriate, post a message to the book’s errata page and fi x the problem in subsequent editions of the book
P2P.WROX.COM
For author and peer discussion, join the P2P forums at http://p2p.wrox.com The forums are a web-based system for you to post messages relating to Wrox books and related technologies and to interact with other readers and technology users The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums Wrox authors, edi-tors, other industry experts, and your fellow readers are present on these forums I try to check the forum on a regular basis, visiting at least several times each week
At http://p2p.wrox.com you can fi nd a number of different forums that to help you not only as you read this book, but also as you develop your own applications To join the forums, just follow these steps:
1. Go to http://p2p.wrox.com and click the Register link
2. Read the terms of use and click Agree
3. Complete the required information to join, as well as any optional information you want to provide, and click Submit
Trang 324. You will receive an e-mail with information describing how to verify your account and
com-plete the joining process
WARNING You can read messages in the forums without joining P2P, but to
post your own messages, you must join After you join, you can post new
mes-sages and respond to mesmes-sages other users post You can read mesmes-sages at
any time on the web If you want to have new messages from a particular forum
e-mailed to you, click the Subscribe to This Forum icon by the forum name in the
forum listing
For more information about how to use the Wrox P2P forum, be sure to read the P2P FAQs for
answers to questions about how the forum software works as well as many common questions
specifi c to P2P and Wrox books To read the FAQs, click the FAQ link on any P2P page
Trang 33with C#
Trang 35Getting Started
CHAPTER 1: Introducing C#
CHAPTER 2: Understanding Objects
Trang 37Introducing C#
WHAT YOU WILL LEARN IN THIS CHAPTER:
‰ How to download Visual Studio
‰ How to install Visual Studio Professional
‰ How to create a simple project
‰ How to develop a small program in Visual Studio
‰ Some features found in the Visual Studio IDE
‰ Running a Visual Studio programWelcome to the world of object-oriented programming and C#! The primary goal of this book is to use the C# programming language from Microsoft to teach you object-oriented programming, or OOP This book assumes that you have no prior programming experience in any language and that you know nothing about OOP As such, this book must be viewed as a
“beginning” text
If you do have programming experience and some familiarity with OOP, that’s fi ne Having that experience makes things easier for you However, I still encourage you to read the book from start to fi nish for a number of reasons First, this book represents the distillation of 25 years of programming and teaching experience I have a good idea of what works and what doesn’t work to explaining complex topics so that they’re easy to understand Reading each chapter gives you the tools to understand the next chapter Second, I may introduce topics
in one chapter and then rely heavily on those topics in a much later chapter In other words, the process used to learn OOP and C# is one that introduces new topics based upon ones that were introduced earlier Obviously, you must master the earlier content before tackling the later content Finally, the programming examples I use also build on concepts presented
1
Trang 38in earlier program examples It will be easier for you to understand the later program examples if
you’ve experimented with those programs introduced earlier in the book
One more thing: You cannot learn programming by just reading about it You have to dig in and
start programming For that reason, there are exercises at the end of each chapter designed to help
you hone your programming skills The learning process is even more interesting if you try to
create your own programs based upon some real problems you’d like to solve Don’t worry if things
don’t fall together instantly on the fi rst try You should plan to make a ton of “fl at-forehead”
mis-takes…you know, the kind of mistake in which, upon discovering it, you pound the heel of your
hand into your forehead and say, “How could I make such a stupid mistake!” Not to worry…we’ve
all been there Such mistakes are just part of the process to become a programmer, and you should
expect to make your fair share However, stick with it, read the book, and you’ll be surprised at
how fast things can come together Indeed, I think you’ll fi nd programming to be a truly enjoyable
pastime
A SHORT HISTORY OF OBJECT-ORIENTED
PROGRAMMING (OOP)
Many people believe that OOP is a product of the 1980s and the work done by Bjarne Stroustrup
in moving the C language into the object-oriented world by creating the C++ language Actually,
SIMULA 1 (1962) and Simula 67 (1967) are the two earliest object-oriented languages The work
on the Simula languages was done by Ole-John Dahl and Kristen Nygaard at the Norwegian
Computing Center in Oslo, Norway Although most of the advantages of OOP were available in the
earlier Simula languages, it wasn’t until C++ became entrenched in the 1990s that OOP began to
fl ourish
C was the parent language of C++ and it was often said that C was powerful enough to shoot
yourself in the foot multiple times C++, on the other hand, not only was powerful enough to
shoot yourself in the foot, but also you could blow your entire leg off without too much diffi culty
Most programmers admit that C++ is a powerful language and it is still in widespread use today
However, with that power comes a lot of complexity Language developers wanted a simpler and
perhaps less complex language for OOP development
The next step in the development of OOP started in January 1991 when James Gosling, Bill Joy,
Patrick Naughton, Mike Sheradin, and several others met in Aspen, Colorado, to discuss ideas for
the Stealth Project The group wanted to develop intelligent electronic devices capable of being
cen-trally controlled and programmed from a handheld device They decided that OOP was the right
direction to go with the development language but felt that C++ was not up to the job The result
was the Oak programming language (named after an oak tree outside Gosling’s window), which
eventually morphed into the Java programming language (Oak had to be renamed because the team
discovered that a language by that name already existed.)
Java quickly grew in popularity, spurred by the growth of the World Wide Web In both cases this
rapid growth was in part because the “guts” necessary to run Java programs on the web quickly
Trang 39became an integral part of various web browsers With the improved web functionality augmented
by Java, the web hit light speed
To many programmers, C# is Microsoft’s answer to Java Some would even say that C# is the result
of Microsoft’s stubbornness to refuse to promote a language it did not develop That sentiment is
a bit too harsh Microsoft had good reasons for developing C#, not the least of which was that it
wanted type-safe programs that run in a managed environment You may not appreciate exactly
what that means right now, but it will become clear as you learn C#
C# provides you with a robust object-oriented programming language and an impressive set of tools
to tackle almost any programming task Whether you want to develop desktop, distributed, web, or mobile applications, C# can handle the task
As you become familiar with C#, you can appreciate its relatively few keywords, its crisp syntax, and its easy-to-use development environment You’ll discover that pieces of programs you write in C# can be reused in other programs Finally, you might appreciate that there are many job opportu-nities for programmers who know C#
INSTALLING C#
If you have already purchased and installed Visual Studio 2012 and C#, you can skip this section
If you haven’t installed C#, this section tells you how to download and install the Visual Studio sion of Visual Studio Visual Studio is a modifi ed version of C# that is available from Microsoft at
ver-no charge Although the Express version of C# is missing some features found in the commercial version of Visual Studio, you should compile and run all the sample programs in this book using Visual Studio
At the present time, the Express version of Visual Studio requires the use of Windows 8 If you do not have Windows 8, you can download a trial version of Visual Studio Professional By registering the trial version, you can use Visual Studio Professional for a period of 90 days After you are con-vinced that you should do all your development work in C# (and you will be), you can purchase the full version of Visual Studio Of course, if you later purchase Windows 8, you can always download the Express version of Visual Studio
Due to the newness of Windows 8, you probably are not using Windows 8 and, hence, must use the trial version of Visual Studio Professional The next section discusses how to download the trial ver-sion of Visual Studio Professional
Downloading Visual Studio Professional
At the time that this book is written, you can go to dio/11/en-us/downloads#professional to download the Professional version of Visual Studio
http://www.microsoft.com/visualstu-The download page should look similar to what is shown in Figure 1-1 As you can see if you look closely at the fi gure, the download is for the 90-day trial version of Visual Studio Professional Click the Install Now button to begin the installation process
Trang 40FIGURE 1-1: Download page for Visual Studio Professional
Depending upon the speed of your system and Internet connection, it can take more than 1 hour to
download and install the 6+ gigabytes of fi les used during the installation process You must fi rst
agree to the licensing terms, as shown in Figure 1-2
After you agree to the licensing terms, the program displays a dialog box that tells you the items
that are about to be installed Unless you are constrained by disk space, you should leave all the
options checked so that they are all installed Otherwise, you can uncheck those options that you do
not want installed See Figure 1-3
Having made your selections, click the Install button to initiate the installation process Your
dis-play will look similar to Figure 1-4 for a long time.