Tải bản đầy đủ

Beginning C# 3.0: An Introduction to Object Oriented Programming pdf

Beginning
C# 3.0
Jack Purdum
Wiley Publishing, Inc.
ffirs.indd iiiffirs.indd iii 4/8/08 1:30:48 PM4/8/08 1:30:48 PM
ffirs.indd iiffirs.indd ii 4/8/08 1:30:47 PM4/8/08 1:30:47 PM
Beginning
C# 3.0
Acknowledgments xi
Introduction xxi
Part I: Getting Started
Chapter 1: Getting Started 3
Chapter 2: Understanding Objects 19
Part II: Understanding C# Syntax
Chapter 3: Understanding Data Types 53
Chapter 4: Understanding C# Statements 75
Chapter 5: Understanding Reference Data Types 99
Chapter 6: Making Decisions in Code 135
Chapter 7: Statement Repetition Using Loops 153
Chapter 8: Arrays 175

Part III: Writing Your Own Classes
Chapter 9: Designing Classes 207
Chapter 10: Designing and Writing Custom Classes 233
Chapter 11: Exception Handling and Debugging 271
Chapter 12: Generics 299
Part IV: Storing Data
Chapter 13: Using Disk Data Files 329
Chapter 14: Using Databases 395
Chapter 15: Inheritance and Polymorphism 443
Appendix A: Exercise Solutions 465
Index 495
ffirs.indd iffirs.indd i 4/8/08 1:30:46 PM4/8/08 1:30:46 PM
ffirs.indd iiffirs.indd ii 4/8/08 1:30:47 PM4/8/08 1:30:47 PM
Beginning
C# 3.0
Jack Purdum
Wiley Publishing, Inc.
ffirs.indd iiiffirs.indd iii 4/8/08 1:30:48 PM4/8/08 1:30:48 PM
Beginning C# 3.0
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2007 by Wiley Publishing, Inc., Indianapolis, Indiana
ISBN: 978-0-470-26129-3
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Library of Congress Cataloging-in-Publication Data:
Purdum, Jack J. (Jack Jay)
Beginning C# 3.0 : an introduction to object oriented programming / Jack Purdum.
p. cm.
Includes index.
ISBN 978-0-470-26129-3 (paper/website)
1. Object-oriented programming (Computer science) 2. C# (Computer program language) I. Title.
QA76.64.P88 2008
005.13'3—dc22
2008011056
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 Legal Department, Wiley Publishing,
Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, 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 specifically
disclaim all warranties, including without limitation warranties of fitness for a particular purpose.
No warranty may be created or extended by sales or promotional 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
publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or
Website 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 Website may provide or
recommendations it may make. Further, readers should be aware that Internet Websites 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 (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related
trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, 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. Wiley Publishing, Inc. is not associated with any product or
vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may
not be available in electronic books.
ffirs.indd ivffirs.indd iv 4/8/08 1:30:48 PM4/8/08 1:30:48 PM
To my children: Katie and John
ffirs.indd vffirs.indd v 4/8/08 1:30:48 PM4/8/08 1:30:48 PM
ffirs.indd viffirs.indd vi 4/8/08 1:30:49 PM4/8/08 1:30:49 PM
About the Author
Dr. 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 software 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. He has been involved with language instruction ever since. Dr. Purdum has
authored 15 texts and numerous programming articles and has received several teaching awards. He is
currently on the cusp of retirement from Purdue University ’ s College of Technology.
ffirs.indd viiffirs.indd vii 4/8/08 1:30:49 PM4/8/08 1:30:49 PM
ffirs.indd viiiffirs.indd viii 4/8/08 1:30:49 PM4/8/08 1:30:49 PM
Acquisitions Editor
Chris Webb
Development Editor
Ed Connor
Technical Editor
Caleb Jenkins
Production Editor
William A. Barton
Copy Editor
S. B. Kleinman
Editorial Manager
Mary Beth Wakefield
Production Manager
Tim Tate
Credits
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Executive Publisher
Joseph B. Wikert
Project Coordinator, Cover
Lynsey Stanford
Proofreaders
Jeremy Bagai,
Josh Chase,
David Fine,
Word One
Indexer
Robert Swanson
ffirs.indd ixffirs.indd ix 4/8/08 1:30:49 PM4/8/08 1:30:49 PM
ffirs.indd xffirs.indd x 4/8/08 1:30:49 PM4/8/08 1:30:49 PM
Acknowledgments
No book is written without massive work by others. Ed Connor, Chris Webb, and a group of editorial
people too numerous to mention have all made this a better book.
A large group of other people also contributed to this book, providing everything from encouragement and
support to ideas for examples. First, thanks to my students who served as guinea pigs for virtually everything
used in this text. Others who played various roles include Tom Bangert, Jay Crannell, Issy Cwynar,
Ann Dotson, Don Dudine, Doug Felkins, Bill Jones, Mark Keenan, Jim McAllister, Bob McFarling, John
Marsh, Katie Mohr, Jeff Nelson, Alice Parker, Larry Powers, Bill Shaw, Mike Shore, Jim Spuller, John Strack,
and John Wilson.
ffirs.indd xiffirs.indd xi 4/8/08 1:30:50 PM4/8/08 1:30:50 PM

ffirs.indd xiiffirs.indd xii 4/8/08 1:30:50 PM4/8/08 1:30:50 PM
Contents
Acknowledgments xi
Introduction xxi
Part I: Getting Started 1
Chapter 1: Getting Started 3
A Short History of Object-Oriented Programming (OOP) 4
Installing C# 5
Downloading C# Express 5
Installing C# Express 6
A Test Program Using C# Express 8
Creating a Project 8
The C# Integrated Development Environment 10
Adding an Object to a Windows Form 12
Running the Program 16
Summary 17
Chapter 2: Understanding Objects 19
Understanding Objects 19
Everyday Use of Objects 20
How Many Properties, How Many Methods? 22
What Do I Do After I’ve Defined a Class? 23
Developing a Program Plan 30
Where to Start? 30
Creating a Simple Application Using Objects 32
Using the Program Steps to Create a Program Plan 33
Using C# to Implement Our Program Plan 35
Adding Program References to Your Project 37
Adding a New Item to the Project 38
Setting the Project Properties 40
Adding Objects to the frmMain Object 41
Adding Program Code for the Process Step 44
ftoc.indd xiiiftoc.indd xiii 4/8/08 5:39:49 PM4/8/08 5:39:49 PM
Contents
xiv
Constructing the User Interface Object 45
The btnDisplayOutput Click Event Code 46
Critique of the btnDisplayOutput Click Event Code 48
Summary 49
Part II: Understanding C# Syntax 51
Chapter 3: Understanding Data Types 53
Integer Data Types 54
Range of Integer Data Types 54
Which Integer Should You Use? 56
Sequence of Steps to Create a New Project 57
Designing the User Interface 58
Code for the Process Step 58
Variable Naming Rules and Conventions 59
Using the TryParse() Method 60
Floating-Point Data Types 63
Floating-Point Precision 65
Which Floating-Point Data Type Should You Use? 67
Monetary Values: The Decimal Data Type 67
Using Intellisense to Locate Program Errors 68
The Boolean Data Type 70
Summary 72
Exercises 73
Chapter 4: Understanding C# Statements 75
Basic Building Blocks of a Programming Language 76
Operands and Operators 76
Expressions 77
Statements 77
Operator Precedence 78
Overriding the Default Precedence Order 79
Defining Variables 80
Defining a Variable from the Compiler’s Point of View 80
Using a Variable in a Program 83
The Bucket Analogy 85
Types of Program Errors 86
Syntax Errors 86
Semantic Errors 87
Logic Errors 87
ftoc.indd xivftoc.indd xiv 4/8/08 5:39:49 PM4/8/08 5:39:49 PM
Contents
xv
The Visual Studio Debugger 87
The Debugging Process 87
Making Repetitious Debugging Easier 88
Using the Debugger 88
Defensive Coding 93
Use Program Comments 93
Use Meaningful Variable Names 95
Avoid Magic Numbers 95
Summary 96
Exercises 97
Chapter 5: Understanding Reference Data Types 99
String Variables 100
Defining a String Reference Variable 100
Why Reference Types are Different From Value Types 103
Reference Variable Rules 104
Reference Type Variables Versus Value Type Variables 105
Why Do Reference Variables Work the Way They Do? 105
Pass by Value versus Pass by Reference 106
A Little Efficiency Gain 106
Using String Variables 107
String Manipulation 108
Strings and Escape Sequences 121
Verbatim String Literals 122
DateTime Reference Objects 123
DateTime and ToString() Conversions 123
Summary 134
Exercises 134
Chapter 6: Making Decisions in Code 135
Relational Operators 136
Using Relational Operators — The if Statement 136
The if-else Statement 140
Shorthand for Simple if-else: The Ternary Operator 141
Style Considerations for if and if-else Statements 142
Nested if Statements 144
RDC 145
Cascading if Statements 146
Logical Operators 147
The switch Statement 150
Summary 152
Exercises 152
ftoc.indd xvftoc.indd xv 4/8/08 5:39:49 PM4/8/08 5:39:49 PM
Contents
xvi
Chapter 7: Statement Repetition Using Loops 153
Program Loops 153
Good Loops, Bad Loops 154
The for Loop 155
Nested for Loops 162
while Loops 165
Why Have More Than One Type of Loop? 166
do-while Program Loops 167
The continue Statement 171
Summary 172
Exercises 173
Chapter 8: Arrays 175
What is an Array? 175
Some Array Details 177
The Listview Object 183
Arrays are Objects 187
Multidimensional Arrays 189
Initializing Arrays 193
Variations for Initializing an Array 193
Initializing Multidimensional Arrays 195
Initializer Lists for Objects 195
Collections 198
ArrayList Objects 200
Summary 203
Exercises 203
Part III: Writing Your Own Classes 205
Chapter 9: Designing Classes 207
Class Design 208
Adding a Class to a Project 208
Scope 209
Visualizing Scope 213
Why Does C# Support Scope? 214
Designing a Program 215
The Five Program Steps 215
Look at the Forest, Not Just the Trees 218
ftoc.indd xviftoc.indd xvi 4/8/08 5:39:50 PM4/8/08 5:39:50 PM
Contents
xvii
UML Light 219
Access Specifiers 219
UML Methods 222
Think Like a User 224
The clsDates Design 225
namespace Modifier 227
Class Organization 227
User Interfaces Versus User Interfaces 231
Summary 232
Exercises 232
Chapter 10: Designing and Writing Custom Classes 233
Constructors 233
Default Constructors 234
Non-Default Constructors 234
Constructor Overloading 235
Property Methods 237
Getters and Setters 238
What to Do if an Error Occurs in a Property Method 242
Class Design for Deck-of-Cards Program 244
UML Class Diagram 245
Designing a Card Game Using clsCardDeck 256
Summary 269
Exercises 270
Chapter 11: Exception Handling and Debugging 271
Overview 271
Bugs 272
Program Errors 273
Data Validation 273
Limit User Input 274
Exception Handling 282
try-catch Statement Blocks 283
Program Debugging 288
The Nature of the Beast 289
The Visual Studio Debugger 291
Single-Stepping Through the Program 294
Scaffold Code 296
Defensive Coding 297
Summary 297
Exercises 298
ftoc.indd xviiftoc.indd xvii 4/8/08 5:39:50 PM4/8/08 5:39:50 PM
Contents
xviii
Chapter 12: Generics 299
What are Generics? 299
Recursion 305
Data Problems 305
What are Generics? 306
Generics Versus ArrayLists 306
Using a Generic Class 314
Generic Quicksort 315
Using Generics with Constraints and Interfaces 319
Interfaces 319
Why Use an Interface? 320
Using an Interface 322
Summary 326
Exercises 326
Part IV: Storing Data 327
Chapter 13: Using Disk Data Files 329
Directories 329
The DriveInfo Class 330
Directory Class 330
DirectoryInfo Class 331
File Namespace 337
FileInfo Class 338
Types of Files 339
Textual Versus Binary Data Files 339
Reading the Data 349
Sequential Versus Random Access Files 350
Sequential Files 350
Random Access Files 351
frmMain 356
Navigating the Records 363
Delete a Record 364
clsRandomAccess 364
Serialization and Deserialization 382
To Serialize or Not to Serialize 388
MDI, Menus, and File Dialogs 388
Adding a Menu 389
Adding a File Open Dialog 390
Calling Another Form 392
ftoc.indd xviiiftoc.indd xviii 4/8/08 5:39:50 PM4/8/08 5:39:50 PM
Contents
xix
Summary 394
Exercises 394
Chapter 14: Using Databases 395
What is a Database? 395
The Structure of a Database 396
Designing Fields for a Database Table 397
Using Your Own Databases 400
ADO.NET 401
Using SQL 402
The SELECT Statement 402
The WHERE Predicate 403
The ORDER BY Clause 403
Aggregates 404
Creating a New Database 406
Creating a New Table (CREATE TABLE) 408
Adding Records to a Table (INSERT INTO) 413
Edit a Record (UPDATE) 416
Delete a Record (DELETE) 421
Database Queries 421
Binding a DataGridView Object to a Database 423
Using a DataGridView Object Without Data Binding 426
Using LINQ 432
LINQ Query Keywords 432
Namespaces and References for LINQ 435
Summary 441
Exercises 442
Chapter 15: Inheritance and Polymorphism 443
What is Inheritance? 443
An Inheritance Example 444
Base Classes are Not Derived Classes 459
Abstract Classes 459
Polymorphism 460
Sending the Snow-Removal Message 462
Summary 463
Exercises 463
Appendix A: Exercise Solutions 465
Index 495
ftoc.indd xixftoc.indd xix 4/8/08 5:39:50 PM4/8/08 5:39:50 PM
ftoc.indd xxftoc.indd xx 4/8/08 5:39:51 PM4/8/08 5:39:51 PM
Introduction
Over the past 25 years I ’ ve written 15 books on various programming topics. You might wonder why so
many . . . Didn ’ t I get it right the first time? Well, no, I didn ’ t . . . not really. When I wrote my first book
over 25 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 filled 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. 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 real question you should be asking yourself is, Why should I buy this book instead of
someone else ’ s book? Good question . . . and a really short answer won ’ t work. A number of factors
come into play, but only one really makes a difference. I have absolutely no doubt that there are
programmers out there who can write better code than I can. When I had my own software company, my
lead programmer, Tim, could code circles around me. He was an amazing coder. But if you asked Tim to
explain something, he fell back toward the end of the line. Indeed, there were times when I thought he
fell off the planet.
The thing that makes this book different from many others is the fact that I ’ ve tried the techniques,
examples, and approach to teaching the various programming concepts on literally thousands of
students. I know what works and what doesn ’ t. I ’ ve suffered through many deer - in - the - headlights
examples, refined and reworked them to the point where I can actually see some students have an
epiphany during the class. 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. What works for you,
the writer, rarely works for everyone else. Writing good code does not necessarily equate to writing good
books. Some charmed people are capable of both (I think P.J. Plauger, Jon Bentley, Brian Kernighan, and
Steve McConnell are examples), but they are rare and far between. Alas, you ’ ve noticed I did not place
myself on the list. However, what I may lack in coding skills is (I think) overcome by my teaching
experience. Obviously, you ’ ll be the final judge.
I think you will find 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.
flast.indd xxiflast.indd xxi 4/8/08 12:53:10 AM4/8/08 12:53:10 AM
Introduction
xxii
Who 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 yourself 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 fine too. This book will likely be an easy read for you.
However, I still think 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.
I think this is the perfect book for someone who knows a programming language but learned that
language before object - oriented programming techniques came into existence. I think 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. I believe this books 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 non - programming - language introduction to object - oriented programming. The
goal of that chapter is to present the concept of objects first and then ease into how objects may be
viewed in C#.
Throughout the book I have tried to use common, easily understood examples to introduce new
programming concepts. I have covered most of the C# programming language, although there are a few
less common topics that I have not covered. I do not feel these omissions are important to the task at
hand, which is to teach you OOP using C#. When you have completed this book, you should feel
comfortable writing complex OOP programs of your own design.
How This Book is Structured
The sequencing of the chapters was dictated by what I use when I teach this class to freshmen
students. The sequence makes logical sense, and each chapter builds upon the information contained in
the previous chapters. While you could skip around, I think this would detract from the learning
experience. I have my own way of explaining things and some are unusual . . . but they work.
flast.indd xxiiflast.indd xxii 4/8/08 12:53:11 AM4/8/08 12:53:11 AM

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×