C++ 2005 For Dummies - Pdf 37

TEAM LinG
by Stephen Randy Davis
and Chuck Sphar
C# 2005
FOR
DUMmIES

01_597043 ffirs.qxd 9/20/05 1:05 PM Page i
C# 2005 For Dummies
®
Published by
Wiley Publishing, Inc.
111 River Street
Hoboken, NJ 07030-5774
www.wiley.com
Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana
Published by Wiley Publishing, 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 permit-
ted 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
/>.
Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the
Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, 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

About the Authors
Stephen R. Davis, who goes by the name of Randy, lives with his wife and son
near Dallas, Texas. He and his family have written numerous books, including
C++ For Dummies and C++ Weekend Crash Course. Stephen works for L-3
Communications.
Chuck Sphar escaped Microsoft’s C++ documentation camps in 1997, after six
years’ hard labor as a senior technical writer. He’s perpetrated two previous
tomes, one on object-oriented programming for the Mac and one on Microsoft’s
MFC class library. He’s currently finishing a novel about ancient Rome
(
againstrome.com
) and gobbling mouthfuls of .NET programming. Chuck
can be reached for praise and minor nits at

.
01_597043 ffirs.qxd 9/20/05 1:05 PM Page iii
01_597043 ffirs.qxd 9/20/05 1:05 PM Page iv
Dedication
For Pam and the Moms — Chuck Sphar
Acknowledgments
I would like to thank Claudette Moore and Debbie McKenna, who
brought the book to me. I also want to thank Randy Davis for being
willing to hand over his baby to a guy he didn’t know. I’d have
found that very hard, and I hope I’ve done justice in extending his
excellent first edition.
Many thanks are due as well to the fine folks at Wiley, starting with
Acquisitions Editor Katie Feltman and Project Editor Kim Darosett.
Kim’s astute shaping helped turn me into a For Dummies author, no
mean feat. I’d also like to thank Chris Bower for his sharp technical
eye and excellent C# knowledge, John Edwards for much of the

)
Composition Services
Project Coordinator: Jennifer Theriot
Layout and Graphics: Carl Byers, Andrea Dahl,
Joyce Haughey, Stephanie D. Jumper,
Heather Ryan, Erin Zeltner
Proofreaders: Leeann Harney,
Carl William Pierce, Dwight Ramsey,
TECHBOOKS Production Services
Indexer: TECHBOOKS Production Services
Publishing and Editorial for Technology Dummies
Richard Swadley, Vice President and Executive Group Publisher
Andy Cummings, Vice President and Publisher
Mary Bednarek, Executive Acquisitions Director
Mary C. Corder, Editorial Director
Publishing for Consumer Dummies
Diane Graves Steele, Vice President and Publisher
Joyce Pepple, Acquisitions Director
Composition Services
Gerry Fahey, Vice President of Production Services
Debbie Stailey, Director of Composition Services
01_597043 ffirs.qxd 9/20/05 1:05 PM Page vi
Contents at a Glance
Introduction ................................................................1
Part I: Creating Your First C# Programs ........................9
Chapter 1: Creating Your First C# Windows Program .................................................11
Chapter 2: Creating Your First C# Console Application .............................................29
Part II: Basic C# Programming ...................................37
Chapter 3: Living with Variability — Declaring Value-Type Variables ......................39
Chapter 4: Smooth Operators ........................................................................................57

What’s New in C# 2.0 ......................................................................................2
About This Book ..............................................................................................3
What You Need to Use the Book ...................................................................3
How to Use This Book ....................................................................................4
How This Book Is Organized ..........................................................................4
Part I: Creating Your First C# Programs .............................................4
Part II: Basic C# Programming .............................................................4
Part III: Object-Based Programming ....................................................5
Part IV: Object-Oriented Programming ...............................................5
Part V: Beyond Basic Classes ...............................................................5
Part VI: The Part of Tens ......................................................................5
About the CD-ROM ................................................................................6
Icons Used in This Book .................................................................................6
Conventions Used in This Book ....................................................................7
Where to Go from Here ...................................................................................7
Part I: Creating Your First C# Programs .........................9
Chapter 1: Creating Your First C# Windows Program . . . . . . . . . . . . .11
Getting a Handle on Computer Languages, C#, and .NET ........................11
What’s a program? ...............................................................................12
What’s C#? ............................................................................................12
What’s .NET? ........................................................................................13
What is Visual Studio 2005? What about Visual C#? .......................14
Creating a Windows Application with C# ...................................................15
Creating the template .........................................................................15
Building and running your first Windows Forms program ............18
Painting pretty pictures ......................................................................20
Make it do something, Daddy ............................................................25
Trying out the final product ...............................................................27
Visual Basic 6.0 programmers, beware! ............................................28
Chapter 2: Creating Your First C# Console Application . . . . . . . . . . . .29

Comparing string and char ..........................................................................53
Declaring Numeric Constants ......................................................................54
Changing Types — The Cast ........................................................................55
Chapter 4: Smooth Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57
Performing Arithmetic ..................................................................................57
Simple operators .................................................................................57
Operating orders .................................................................................58
The assignment operator ...................................................................60
The increment operator .....................................................................61
Performing Logical Comparisons — Is That Logical? ..............................62
Comparing floating point numbers:
Is your float bigger than mine? ......................................................63
Compounding the confusion with
compound logical operations ........................................................64
Finding the Perfect Date — Matching Expression Types .........................66
Calculating the type of an operation ................................................67
Assigning types ....................................................................................68
The Ternary Operator — I Wish It Were a Bird and Would Fly Away ........69
Chapter 5: Controlling Program Flow . . . . . . . . . . . . . . . . . . . . . . . . . . .71
Controlling Program Flow ............................................................................72
Introducing the if statement ..............................................................73
Examining the else statement ............................................................75
Avoiding even the else ........................................................................76
Embedded if statements .....................................................................77
C# 2005 For Dummies
x
02_597043 ftoc.qxd 9/20/05 1:05 PM Page x
Looping Commands ......................................................................................80
Introducing the while loop .................................................................80
Using the do...while loop ....................................................................84

Having Arguments with Functions ............................................................135
Passing an argument to a function ..................................................136
Passing multiple arguments to functions .......................................136
Matching argument definitions with usage ....................................138
Overloading a function does not mean
giving it too much to do ................................................................139
Implementing default arguments .....................................................140
Passing value-type arguments .........................................................142
Returning Values after Christmas .............................................................147
Returning a value via return postage ..............................................147
Returning a value using pass by reference ....................................148
When do I return and when do I out? .............................................149
Defining a function with no value ....................................................152
xi
Table of Contents
02_597043 ftoc.qxd 9/20/05 1:05 PM Page xi
The Main( ) Deal — Passing Arguments to a Program ...........................153
Passing arguments from a DOS prompt ..........................................155
Passing arguments from a window .................................................157
Passing arguments from Visual Studio 2005 ..................................159
Chapter 8: Class Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .163
Passing an Object to a Function ................................................................163
Defining Object Functions and Methods ..................................................165
Defining a static member function ..................................................165
Defining a method .............................................................................167
Expanding a method’s full name .....................................................168
Accessing the Current Object ....................................................................169
What is the this keyword? ................................................................171
When is this explicit? ........................................................................172
What happens when I don’t have this? ...........................................174

C# 2005 For Dummies
xii
02_597043 ftoc.qxd 9/20/05 1:05 PM Page xii
Chapter 11: Holding a Class Responsible . . . . . . . . . . . . . . . . . . . . . .221
Restricting Access to Class Members ......................................................221
A public example of public BankAccount ......................................222
Jumping ahead — other levels of security .....................................224
Why Worry about Access Control? ...........................................................225
Accessor methods .............................................................................226
Access control to the rescue — an example ..................................227
So what? ..............................................................................................230
Defining class properties ..................................................................231
Getting Your Objects Off to a Good Start — Constructors ....................233
The C#-Provided Constructor ...................................................................233
The Default Constructor ............................................................................235
Constructing something ...................................................................236
Executing the constructor from the debugger ..............................238
Initializing an object directly — the default constructor .............241
Seeing that construction stuff with initializers ..............................242
Overloading the Constructor (Is That Like
Overtaxing a Carpenter?) .......................................................................243
Avoiding Duplication among Constructors .............................................245
Being Object Stingy .....................................................................................249
Chapter 12: Inheritance — Is That All I Get? . . . . . . . . . . . . . . . . . . . .251
Inheriting a Class .........................................................................................252
Why Do You Need Inheritance? .................................................................253
A More Involved Example — Inheriting from a BankAccount Class ......254
IS_A versus HAS_A — I’m So Confused ....................................................257
The IS_A relationship ........................................................................257
Gaining access to BankAccount through containment ................258

Restarting a Class Hierarchy .....................................................................296
Sealing a Class .............................................................................................300
Part V: Beyond Basic Classes ....................................301
Chapter 14: When a Class Isn’t a Class —
The Interface and the Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .303
What Is CAN_BE_USED_AS? .......................................................................303
What Is an Interface? ..................................................................................305
Can I Get a Short Example? ........................................................................306
Can I See a Program That CAN_BE_USED_AS an Example? ...................307
Creating your own interface at home in your spare time ............308
Predefined interfaces ........................................................................309
Putting it all together ........................................................................311
Inheriting an Interface ................................................................................316
Facing an Abstract Interface ......................................................................316
The C# Structure Has No Class .................................................................319
The C# structure ................................................................................320
The structure constructor ...............................................................322
The wily methods of a structure .....................................................323
Putting a struct through its paces in an example .........................323
“Oh, the Value and the Reference Can Be Friends . . .” —
Unifying the Type System .......................................................................327
Predefined structure types ..............................................................327
So, how do common structures unify the type system?
An example .....................................................................................328
Boxing and unboxing value types ...................................................330
Chapter 15: Asking Your Pharmacist about Generics . . . . . . . . . . . .333
Getting to Know Nongeneric Collections .................................................334
Inventorying nongeneric collections ..............................................334
Using nongeneric collections ...........................................................335
Writing a New Prescription: Generics .......................................................336

‘className.memberName’ is inaccessible
due to its protection level ............................................................371
Use of unassigned local variable ‘n’ ................................................372
Unable to copy the file ‘programName.exe’ to
‘programName.exe’. The process cannot . . . .............................373
‘subclassName.methodName’ hides inherited member
‘baseclassName.methodName’. Use the new keyword
if hiding was intended ...................................................................374
‘subclassName’ : cannot inherit from sealed class
‘baseclassName’ .............................................................................375
‘className’ does not implement interface member
‘methodName’ ................................................................................376
‘methodName’ : not all code paths return a value ........................376
} expected ...........................................................................................377
Chapter 17: The 10 Most Significant Differences
between C# and C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .379
No Global Data or Functions ......................................................................380
All Objects Are Allocated Off the Heap ....................................................380
Pointer Variables Are All but Disallowed .................................................381
C# Generics Are Like C++ Templates — or Are They? ............................381
I’ll Never Include a File Again ....................................................................382
Don’t Construct — Initialize ......................................................................382
xv
Table of Contents
02_597043 ftoc.qxd 9/20/05 1:05 PM Page xv
Define Your Variable Types Well ...............................................................383
No Multiple Inheriting .................................................................................383
Projecting a Good Interface .......................................................................383
Unified Type System ...................................................................................384
Appendix: About the CD ............................................385

Using a namespace .........................................................................CD35
How about using a fully qualified example? ...............................CD36
Collecting Classes into Class Libraries .................................................CD39
Creating a class library project ....................................................CD39
Creating classes for the library ....................................................CD40
Creating a “driver” project ............................................................CD41
C# 2005 For Dummies
xvi
02_597043 ftoc.qxd 9/20/05 1:05 PM Page xvi
Collecting Data into Files ........................................................................CD43
Using StreamWriter ........................................................................CD45
Improving your reading speed and
comprehension through StreamReader ...................................CD50
Bonus Chapter 3: Stepping through Collections . . . . . . . . . . . . . . .CD55
Iterating through a Directory of Files ....................................................CD55
Writing Your Own Collection Class: The Linked List ...........................CD62
An example linked-list container ..................................................CD63
Why bother with a linked list? ......................................................CD73
Iterating foreach Collections: Iterators .................................................CD73
Accessing a collection: The general problem .............................CD74
Letting C# access data foreach container ...................................CD76
Accessing Collections the Array Way: Indexers ...................................CD77
Indexer format ................................................................................CD78
Example indexer program .............................................................CD78
Looping around the Iterator Block ........................................................CD82
Iterating days of the month: A first example ..............................CD87
What’s a collection, really? ...........................................................CD89
Iterator syntax gives up so easily .................................................CD90
Iterator blocks of all shapes and sizes ........................................CD92
Where to put your iterator ............................................................CD95

Working Without a Net — But Not a .NET ...........................................CD140
Grabbing the free ingredients .....................................................CD141
Going around the C# development cycle ..................................CD142
Doing C# with SharpDevelop ................................................................CD142
Examining SharpDevelop ............................................................CD143
Comparing SharpDevelop features with Visual Studio ............CD144
Getting help ...................................................................................CD145
Configuring SharpDevelop ..........................................................CD146
Adding a tool to launch the debugger .......................................CD146
Running the debugger from SharpDevelop ...............................CD147
Missing debugger stuff ................................................................CD150
Doing C# with TextPad ..........................................................................CD150
Creating a C# .CS document class ..............................................CD153
Adding a tool of your own: Build C# Debug ..............................CD155
Configuring a tool to do a Release build ...................................CD157
Explaining the configuration options
for the Debug and Release tools .............................................CD158
Dealing with compiler errors ......................................................CD162
Configuring the rest of the tools ................................................CD162
Testing It with NUnit ..............................................................................CD165
Running NUnit ...............................................................................CD166
Testing? I have to do testing? .....................................................CD166
Writing NUnit tests .......................................................................CD168
Debugging bugs in your test code ..............................................CD175
Writing Windows Forms Code without a Form Designer ..................CD177
It’s just code ..................................................................................CD177
Doing it the designer’s way .........................................................CD178
Understanding the new partial classes .....................................CD179
Doing it your own way .................................................................CD180
Making Sure Your Users Can Run Your C# Programs ........................CD180

Mono lags Microsoft’s .NET, just now implementing the 1.1 version that
Microsoft released a couple of years ago, it appears to be moving fast.
ߜ Portable .NET, under the banner of Southern Storm Software and DotGNU
(
www.dotgnu.org/pnet.html
), is also open-source. Portable .NET is at
version 0.7.0 as of this writing.
Both Mono and Portable .NET claim to run C# programs on Windows and a
variety of Unix flavors, including Linux and Apple’s Macintosh operating
system. At this writing, Portable .NET reaches the greater number of flavors,
while Mono boasts a more complete .NET implementation. So choosing
between them can be complicated, depending on your project, your platform,
and your goals. (Books about programming for these platforms are becoming
available already. Check
www.amazon.com
.)
Open-source software is written by collaborating groups of volunteer pro-
grammers and is usually free to the world.
03_597043 intro.qxd 9/20/05 1:07 PM Page 1
Making C# and other .NET languages portable to other operating systems is
far beyond the scope of this book. But you can expect that within a few years,
the C# Windows programs you discover how to write in this book will run on
all sorts of hardware under all sorts of operating systems — matching the
claim of Sun Microsystems’ Java language to run on any machine. That’s
undoubtedly a good thing, even for Microsoft. The road to that point is still
under construction, so it’s no doubt riddled with potholes and obstacles to
true universal portability for C#. But it’s no longer just Microsoft’s road.
For the moment, however, Microsoft’s Visual Studio has the most mature
versions of C# and .NET and the most feature-filled toolset for programming
with them.

using Microsoft Visual Studio, although we do provide alternatives. In basing
the book on Visual Studio, we’ve tried to keep the Visual Studio portions to a
reasonable minimum. we could just tell you, “Run your program any way you
want,” but instead we may say, “Execute your C# program from Visual Studio
by pressing F5.” We want you to be able to focus on the C# language and not
on the mechanics of getting simple things to work.
We realize that many, if not most, readers will want to use C# to write graphi-
cal Windows applications. C# is a powerful tool for programming graphical
Windows applications, but that’s only one area for using C#, and this book
must focus on C# as a language. We touch briefly on graphical Windows pro-
grams in Chapter 1, but you should get a good grasp of C# before seeking
another source to understand Windows programming in full. We also realize
that some power users will be using C# to build Web-ready, distributed appli-
cations; however, publishing limitations require us to draw the line some-
where. C# 2005 For Dummies does not tackle the challenges of distributed
programming. The book does explain quite a bit of .NET, though, for the
simple reason that much of C#’s power comes from the .NET Framework
class libraries that it uses.
What You Need to Use the Book
At a minimum, you need the Common Language Runtime (CLR) before you
can even execute the programs generated by C#. Visual Studio 2005 copies
the CLR onto your machine for you as part of the installation procedure.
Alternatively, you can download the entire .NET package, including the C#
compiler and many other nice tools, from Microsoft’s Web site at
http://
msdn.microsoft.com
. Look for the .NET Software Development Toolkit
(SDK). Bonus Chapter 5 on the CD explains how to get these items.
You can still create most of the programs in this book with Visual Studio
2003, if you need to. The exceptions are those that cover the new features

used in the other parts of this book.
Part II: Basic C# Programming
At the most basic level, Shakespeare’s plays are just a series of words all
strung together. By the same token, 90 percent of any C# program you ever
write consists of creating variables, performing arithmetic operations, and
controlling the execution path through a program. This part concentrates on
these core operations.
4
C# 2005 For Dummies
03_597043 intro.qxd 9/20/05 1:07 PM Page 4
Part III: Object-Based Programming
It’s one thing to declare variables here or there and to add them and subtract
them. It’s quite another thing to write real programs for real people. Part III
focuses on how to organize your data to make it easier to use in creating a
program.
Part IV: Object-Oriented Programming
You can organize the parts of an airplane all you want, but until you make it
do something, it’s nothing more than a collection of parts. It’s not until you
fire up the engines and start the wings flapping that it’s going anywhere.
In like fashion, Part IV explains how to turn a collection of data into a real
object — an object that has internal members, sure, but an object that can
mimic the properties of a real-world item. This part presents the essence of
object-oriented programming.
Part V: Beyond Basic Classes
After the airplane gets off the ground, it has to go somewhere. Figuring out
classes and the fundamentals of object-oriented programming is only a start.
Part V takes the next step, introducing structures, interfaces, and generics,
your gateway to more advanced object-oriented concepts — and the wild
blue yonder.
Part VI: The Part of Tens

important information.
This icon flags technical stuff that you can skip on the first reading.
The Tip icon highlights a point that can save you a lot of time and effort.
Remember this. It’s important.
Remember this, too. This one can sneak up on you when you least expect it
and generate one of those really hard-to-find bugs.
This icon identifies code that you can find on the CD-ROM that comes with
this book. This feature is designed to save you some typing when your fin-
gers start to cramp, but don’t abuse it. You’ll gain a better understanding of
C# by entering the programs yourself.
6
C# 2005 For Dummies
03_597043 intro.qxd 9/20/05 1:07 PM Page 6


Nhờ tải bản gốc
Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status