Table Of ContentC# 2010
ALL-IN-ONE
FOR
DUMmIES
‰
by Bill Sempf, Chuck Sphar,
and Stephen Randy Davis
0011__556633448899--ffffiirrss..iinndddd ii 33//2222//1100 55::2299 PPMM
C# 2010 All-in-One For Dummies®
Published by
Wiley Publishing, Inc.
111 River Street
Hoboken, NJ 07030-5774
www.wiley.com
Copyright © 2010 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
http://www.wiley.com/go/permissions.
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 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. Wiley Publishing, Inc., is not associated with any product or vendor
mentioned in this book.
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 WITH-
OUT 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 ORGANIZA-
TION 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 U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
For technical support, please visit www.wiley.com/techsupport.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may
not be available in electronic books.
Library of Congress Control Number: TK
ISBN: 978-0-470-56348-9
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
0011__556633448899--ffffiirrss..iinndddd iiii 33//2222//1100 55::2299 PPMM
Table of Contents
Introduction ................................................................. 1
What’s New in C# 4.0 .......................................................................................2
About This Book ..............................................................................................3
What You Need in Order to Use This Book ..................................................3
How to Use This Book .....................................................................................4
How This Book Is Organized ..........................................................................4
Book I: The Basics of C# Programming ...............................................5
Book II: Object-Oriented C# Programming .........................................5
Book III: Designing for C# ......................................................................5
Book IV: A Tour of Visual Studio ..........................................................5
Book V: Windows Development with WPF .........................................5
Book VI: Web Development with ASP.NET .........................................6
Book VII: Service-Oriented Development ............................................6
Book VIII: New Features in C# 4.0 ........................................................6
Icons Used in This Book .................................................................................6
Conventions Used in This Book .....................................................................7
About this book’s Web site ...................................................................7
Where to Go from Here ...................................................................................8
Book I: Basics of C# Programming ................................. 9
Chapter 1: Creating Your First C# Console Application. . . . . . . . . . . . .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 2010? What about Visual C#? .......................14
Creating Your First Console Application ....................................................14
Creating the source program .............................................................15
Taking it out for a test drive ...............................................................18
Making Your Console App Do Something ...................................................19
Reviewing Your Console Application ..........................................................20
The program framework .....................................................................20
Comments .............................................................................................21
The meat of the program ....................................................................21
Introducing the Toolbox Trick .....................................................................22
Saving code in the Toolbox ................................................................23
Reusing code from the Toolbox .........................................................23
0022__556633448899--ffttoocc..iinndddd iixx 33//1199//1100 88::0011 PPMM
x
C# 2010 All-in-One For Dummies
Chapter 2: Living with Variability — Declaring
Value-Type Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .25
Declaring a Variable ......................................................................................25
What’s an int? .................................................................................................26
Rules for declaring variables ..............................................................27
Variations on a theme: Different types of int ...................................27
Representing Fractions .................................................................................28
Handling Floating-Point Variables ...............................................................29
Declaring a fl oating-point variable .....................................................30
Converting some more temperatures ...............................................31
Examining some limitations of fl oating-point variables ..................31
Using the Decimal Type: Is It an Integer or a Float? ..................................32
Declaring a decimal .............................................................................33
Comparing decimals, integers, and fl oating-point types ................33
Examining the bool Type: Is It Logical? ......................................................34
Checking Out Character Types ....................................................................34
The char variable type ........................................................................34
Special chars ........................................................................................35
The string type .....................................................................................35
What’s a Value Type? ....................................................................................36
Comparing string and char ...........................................................................37
Calculating Leap Years: DateTime ...............................................................38
Declaring Numeric Constants ......................................................................40
Changing Types: The Cast ............................................................................41
Letting the C# Compiler Infer Data Types ..................................................42
Chapter 3: Pulling Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45
The Union Is Indivisible, and So Are Strings ..............................................46
Performing Common Operations on a String .............................................47
Comparing Strings .........................................................................................48
Equality for all strings: The Compare() method .............................48
Would you like your compares with or without case?....................51
What If I Want to Switch Case? ....................................................................52
Distinguishing between all-uppercase and all-lowercase strings ....52
Converting a string to upper- or lowercase ......................................52
Looping through a String ..............................................................................53
Searching Strings ...........................................................................................54
Can I fi nd it? ..........................................................................................54
Is my string empty? .............................................................................55
Getting Input from the Command Line .......................................................55
Trimming excess white space ............................................................55
Parsing numeric input .........................................................................56
Handling a series of numbers .............................................................58
Joining an array of strings into one string ........................................60
Controlling Output Manually .......................................................................60
Using the Trim() and Pad() methods ...............................................61
Using the Concatenate() method ......................................................63
Let’s Split() that concatenate program ............................................64
0022__556633448899--ffttoocc..iinndddd xx 33//1199//1100 88::0011 PPMM
xi
Table of Contents
Formatting Your Strings Precisely ..............................................................65
StringBuilder: Manipulating Strings More Effi ciently ................................69
Chapter 4: Smooth Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73
Performing Arithmetic ..................................................................................73
Simple operators ..................................................................................73
Operating orders ..................................................................................74
The assignment operator ....................................................................75
The increment operator ......................................................................76
Performing Logical Comparisons — Is That Logical? ...............................77
Comparing fl oating-point numbers: Is your fl oat
bigger than mine? .............................................................................78
Compounding the confusion with compound
logical operations .............................................................................79
Matching Expression Types at TrackDownAMate.com ............................80
Calculating the type of an operation .................................................81
Assigning types ....................................................................................82
Chapter 5: Getting Into the Program Flow . . . . . . . . . . . . . . . . . . . . . . . .85
Branching Out with if and switch ................................................................86
Introducing the if statement ...............................................................86
Examining the else statement ............................................................89
Avoiding even the else ........................................................................90
Nesting if statements ...........................................................................90
Running the switchboard....................................................................92
Here We Go Loop-the-Loop ..........................................................................95
Looping for a while ..............................................................................95
Doing the do . . . while loop ................................................................99
Breaking up is easy to do ....................................................................99
Looping until you get it right ............................................................100
Focusing on scope rules ...................................................................103
Looping a Specifi ed Number of Times with for .......................................104
An example .........................................................................................105
Why do you need another loop? ......................................................105
Nesting Loops ..............................................................................................106
Don’t goto Pieces .........................................................................................107
Chapter 6: Lining Up Your Ducks with Collections . . . . . . . . . . . . . . .109
The C# Array ................................................................................................109
The argument for the array ..............................................................110
The fi xed-value array .........................................................................110
The variable-length array .................................................................112
The Length property .........................................................................114
Initializing an array ............................................................................115
A Loop Made foreach Array ....................................................................115
Sorting Arrays of Data .................................................................................116
New Feature: Using var for Arrays ............................................................120
Loosening Up with C# Collections .............................................................121
0022__556633448899--ffttoocc..iinndddd xxii 33//1199//1100 88::0011 PPMM
xii
C# 2010 All-in-One For Dummies
Understanding Collection Syntax ..............................................................122
Figuring out <T> .................................................................................123
Going generic ......................................................................................124
Using Lists ....................................................................................................124
Using Dictionaries .......................................................................................126
Array and Collection Initializers ................................................................128
Initializing arrays ...............................................................................128
Initializing collections .......................................................................129
Using Sets .....................................................................................................130
On Not Using Old-Fashioned Collections .................................................134
Chapter 7: Stepping through Collections. . . . . . . . . . . . . . . . . . . . . . . .135
Iterating through a Directory of Files ........................................................135
Iterating foreach Collections: Iterators .....................................................141
Accessing a collection: The general problem ................................141
Letting C# access data foreach container ......................................143
Accessing Collections the Array Way: Indexers ......................................145
Indexer format ....................................................................................145
An indexer program example ...........................................................146
Looping Around the Iterator Block ...........................................................150
Iterating days of the month: A fi rst example ..................................154
What a collection is, really ...............................................................155
Iterator syntax gives up so easily ....................................................156
Iterator blocks of all shapes and sizes ............................................158
Where you can put your iterator .....................................................161
Chapter 8: Buying Generic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .169
Writing a New Prescription: Generics .......................................................169
Generics are type-safe .......................................................................170
Generics are effi cient .........................................................................171
Classy Generics: Writing Your Own ..........................................................171
Shipping packages at OOPs ..............................................................172
Queuing at OOPs: PriorityQueue .....................................................172
Unwrapping the package ..................................................................177
Touring Main() ...................................................................................178
Writing generic code the easy way ..................................................179
Saving PriorityQueue for last ...........................................................180
Using a (nongeneric) Simple Factory class ....................................182
Tending to unfi nished business .......................................................184
Chapter 9: Some Exceptional Exceptions . . . . . . . . . . . . . . . . . . . . . . .187
Using an Exceptional Error-Reporting Mechanism .................................187
About try blocks ................................................................................189
About catch blocks ............................................................................189
About fi nally blocks ...........................................................................190
What happens when an exception is thrown .................................190
Throwing Exceptions Yourself ...................................................................192
0022__556633448899--ffttoocc..iinndddd xxiiii 33//1199//1100 88::0011 PPMM
xiii
Table of Contents
Knowing What Exceptions Are For ............................................................192
Can I Get an Exceptional Example? ...........................................................193
Knowing what makes the example exceptional .............................194
Tracing the stack ...............................................................................195
Assigning Multiple catch Blocks ................................................................196
Planning Your Exception-Handling Strategy ............................................198
Some questions to guide your planning .........................................198
Guidelines for code that handles errors well .................................199
How to analyze a method for possible exceptions ........................200
How to fi nd out which methods throw which exceptions............203
Grabbing Your Last Chance to Catch an Exception ................................203
Book II: Object-Oriented C# Programming .................. 205
Chapter 1: Object-Oriented Programming: What’s It All About? . . . . .207
Object-Oriented Concept #1: Abstraction ................................................207
Preparing procedural nachos...........................................................208
Preparing object-oriented nachos ...................................................209
Object-Oriented Concept #2: Classifi cation .............................................209
Why Classify? ...............................................................................................210
Object-Oriented Concept #3: Usable Interfaces ......................................211
Object-Oriented Concept #4: Access Control ..........................................212
How C# Supports Object-Oriented Concepts ..........................................212
Chapter 2: Showing Some Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .215
Defi ning a Class and an Object ..................................................................215
Defi ning a class ...................................................................................216
What’s the object? .............................................................................217
Accessing the Members of an Object ........................................................218
An Object-Based Program Example ..........................................................218
Discriminating between Objects ................................................................220
Can You Give Me References? ....................................................................221
Classes That Contain Classes Are the Happiest
Classes in the World ................................................................................223
Generating Static in Class Members .........................................................224
Defi ning const and readonly Data Members .......................................225
Chapter 3: We Have Our Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .227
Defi ning and Using a Method .....................................................................227
A Method Example for Your Files ..............................................................229
Having Arguments with Methods ..............................................................236
Passing an argument to a method ...................................................236
Passing multiple arguments to methods ........................................237
Matching argument defi nitions with usage ....................................238
Overloading a method doesn’t mean giving it too much to do ...239
Implementing default arguments .....................................................240
0022__556633448899--ffttoocc..iinndddd xxiiiiii 33//1199//1100 88::0011 PPMM
xiv
C# 2010 All-in-One For Dummies
Returning Values after Christmas .............................................................243
Returning a value via return postage ..............................................243
Defi ning a method with no value .....................................................244
Chapter 4: Let Me Say This about this . . . . . . . . . . . . . . . . . . . . . . . .247
Passing an Object to a Method ..................................................................247
Defi ning Methods .........................................................................................249
Defi ning a static method ...................................................................249
Defi ning an instance method ............................................................250
Expanding a method’s full name ......................................................252
Accessing the Current Object ....................................................................253
What is the this keyword? ..............................................................254
When is this explicit? ......................................................................255
What happens when you don’t have this? ...................................257
Chapter 5: Holding a Class Responsible . . . . . . . . . . . . . . . . . . . . . . . .261
Restricting Access to Class Members .......................................................261
A public example of public BankAccount .......................................262
Jumping ahead — other levels of security .....................................264
Why You Should Worry about Access Control ........................................265
Accessor methods .............................................................................266
Access control to the rescue — an example ..................................266
So what? ..............................................................................................269
Defi ning Class Properties ...........................................................................270
Static properties ................................................................................271
Properties with side effects ..............................................................272
New feature: Letting the compiler write properties for you ........272
Accessors with access levels ...........................................................273
Getting Your Objects Off to a Good Start — Constructors ....................273
The C#-Provided Constructor ....................................................................274
Replacing the Default Constructor ............................................................275
Constructing something ....................................................................276
Executing the constructor from the debugger ...............................278
Initializing an object directly with an initializer ............................281
Seeing that construction stuff with initializers ..............................282
New feature: Initializing an object without a constructor ............283
Chapter 6: Inheritance: Is That All I Get?. . . . . . . . . . . . . . . . . . . . . . . .285
Class Inheritance .........................................................................................286
Why You Need Inheritance .........................................................................287
Inheriting from a BankAccount Class (A More Complex Example) ......288
IS_A versus HAS_A — I’m So Confused_A ................................................291
The IS_A relationship ........................................................................291
Gaining access to BankAccount by using containment ................292
The HAS_A relationship ....................................................................293
When to IS_A and When to HAS_A ............................................................293
0022__556633448899--ffttoocc..iinndddd xxiivv 33//1199//1100 88::0011 PPMM
xv
Table of Contents
Other Features That Support Inheritance ................................................294
Substitutable classes .........................................................................294
Invalid casts at run time....................................................................295
Avoiding invalid conversions with the is operator .......................296
Avoiding invalid conversions with the as operator ......................297
The object Class ..........................................................................................297
Inheritance and the Constructor ...............................................................298
Invoking the default base class constructor ..................................298
Passing arguments to the base class constructor —
mama sang base .............................................................................300
Getting specifi c with base .................................................................301
The Updated BankAccount Class ..............................................................302
Chapter 7: Poly-what-ism?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .307
Overloading an Inherited Method .............................................................308
It’s a simple case of method overloading .......................................308
Different class, different method .....................................................308
Peek-a-boo — hiding a base class method .....................................309
Calling back to base ...........................................................................313
Polymorphism ..............................................................................................314
Using the declared type every time (Is that so wrong?) ...............316
Using is to access a hidden method polymorphically ................318
Declaring a method virtual and overriding it .................................319
Getting the most benefi t from polymorphism —
the do-to-each trick ........................................................................321
The Class Business Card: ToString() ........................................................321
C# During Its Abstract Period ....................................................................322
Class factoring ....................................................................................322
The abstract class: Left with nothing but a concept .....................327
How do you use an abstract class? .................................................328
Creating an abstract object — not! ..................................................330
Sealing a Class ..............................................................................................330
Chapter 8: Interfacing with the Interface. . . . . . . . . . . . . . . . . . . . . . . .333
Introducing CAN_BE_USED_AS ..................................................................333
Knowing What an Interface Is ....................................................................335
How to implement an interface ........................................................335
How to name your interface .............................................................336
Why C# includes interfaces ..............................................................336
Mixing inheritance and interface implementation ........................336
And he-e-e-re’s the payoff .................................................................337
Using an Interface ........................................................................................338
As a method return type ...................................................................338
As the base type of an array or collection ......................................339
As a more general type of object reference ...................................339
Using the C# Predefi ned Interface Types .................................................339
0022__556633448899--ffttoocc..iinndddd xxvv 33//1199//1100 88::0011 PPMM
xvi
C# 2010 All-in-One For Dummies
Looking at a Program That CAN_BE_USED_AS an Example ...................340
Creating your own interface at home in your spare time .............340
Implementing the incomparable IComparable<T> interface........341
Putting it all together.........................................................................343
Getting back to the Main() event ....................................................346
Unifying Class Hierarchies .........................................................................346
Hiding Behind an Interface .........................................................................348
Inheriting an Interface .................................................................................351
Using Interfaces to Manage Change in Object-Oriented Programs .......352
Making fl exible dependencies through interfaces .........................353
Abstract or concrete: When to use an abstract class
and when to use an interface ........................................................353
Doing HAS_A with interfaces ............................................................354
Chapter 9: Delegating Those Important Events. . . . . . . . . . . . . . . . . . .357
E.T., Phone Home — The Callback Problem ............................................357
Defi ning a Delegate ......................................................................................358
Pass Me the Code, Please — Examples .....................................................360
I delegated the example to Igor ........................................................360
First, a simple example .....................................................................361
A More Real-World Example ......................................................................362
Getting an overview of the bigger example ....................................363
Putting the app together ...................................................................363
Looking at the code ...........................................................................365
Tracking the delegate life cycle .......................................................366
Shh! Keep It Quiet — Anonymous Methods .............................................368
Stuff Happens — C# Events ........................................................................369
The Observer design pattern ...........................................................369
What’s an event? Publish/Subscribe ...............................................370
How a publisher advertises its events ............................................370
How subscribers subscribe to an event .........................................371
How to publish an event ...................................................................372
How to pass extra information to an event handler ......................372
A recommended way to raise your events .....................................373
How observers “handle” an event ...................................................374
Chapter 10: Can I Use Your Namespace in the Library? . . . . . . . . . . .377
Dividing a Single Program into Multiple Source Files .............................378
Dividing a Single Program into Multiple Assemblies ..............................379
Executable or library? .......................................................................379
Assemblies ..........................................................................................380
Executables .........................................................................................381
Class libraries .....................................................................................381
Putting Your Classes into Class Libraries ................................................382
Creating the projects for a class library .........................................382
Creating a stand-alone class library ................................................382
Adding a second project to an existing solution ...........................383
0022__556633448899--ffttoocc..iinndddd xxvvii 33//1199//1100 88::0011 PPMM