Join the discussion @ p2p.wrox.com
Wrox Programmer to Programmer™
Beginning
Visual C# 2010
®
Karli Watson, Christian Nagel, Jacob Hammer Pedersen, Jon D. Reid, Morgan Skinner
www.it-ebooks.info
Programmer to Programmer™
Get more out of
wrox.com
Interact
Join the Community
Take an active role online by participating in our
P2P forums @ p2p.wrox.com
Sign up for our free monthly newsletter at
newsletter.wrox.com
Wrox Online Library
Browse
Hundreds of our books are available online
through Books24x7.com
Ready for more Wrox? We have books and
e-books available on .NET, SQL Server, Java,
XML, Visual Basic, C#/ C++, and much more!
Wrox Blox
Download short informational pieces and code
to keep you up to date and out of trouble!
Contact Us.
We always like to get feedback from our readers. Have a book idea?
Need community support? Let us know by e-mailing
www.it-ebooks.info
BEGINNING VISUAL C# 2010
INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiii
PART I
THE C# LANGUAGE
CHAPTER 1
Introducing C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
CHAPTER 2
Writing a C# Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
CHAPTER 3
Variables and Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
CHAPTER 4
Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
CHAPTER 5
More About Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
CHAPTER 6
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
CHAPTER 7
Debugging and Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
CHAPTER 8
Introduction to Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . 185
CHAPTER 9
Defining Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
CHAPTER 10
Defining Class Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
CHAPTER 11
Collections, Comparisons, and Conversions . . . . . . . . . . . . . . . . . . . . . 277
CHAPTER 12
Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
CHAPTER 13
Additional OOP Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
CHAPTER 14
C# Language Enhancements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
PART II
WINDOWS PROGRAMMING
CHAPTER 15
Basic Windows Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
CHAPTER 16
Advanced Windows Forms Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
CHAPTER 17
Deploying Windows Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
PART III
WEB PROGRAMMING
CHAPTER 18
ASP.NET Web Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
CHAPTER 19
Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637
CHAPTE
Continues
www.it-ebooks.info
PART IV
DATA ACCESS
CHAPTER 21
File System Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
CHAPTER 22
XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725
CHAPTER 23
Introduction to LINQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
CHAPTER 24
Applying LINQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
PART V
ADDITIONAL TECHNIQUES
CHAPTER 25
Windows Presentation Foundation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 829
CHAPTER 26
Windows Communication Foundation . . . . . . . . . . . . . . . . . . . . . . . . . . 899
CHAPTER 27
Windows Workflow Foundation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 935
APPENDIX A
Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 957
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1009
www.it-ebooks.info
BEGINNING
Visual C# 2010
www.it-ebooks.info
www.it-ebooks.info
BEGINNING
Visual C# 2010
Karli Watson
Christian Nagel
Jacob Hammer Pedersen
Jon Reid
Morgan Skinner
Wiley Publishing, Inc.
www.it-ebooks.info
Beginning Visual C# 2010
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-50226-6
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
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) 748-6011, fax (201) 7486008, or online at />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 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 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: 2010920663
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. C# is a registered trademark of Microsoft Corporation in the United States
and/or other countries. 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.
www.it-ebooks.info
for Donna
— Karli Watson
www.it-ebooks.info
www.it-ebooks.info
ABOUT THE AUTHORS
KARLI WATSON is consultant at Infusion Development (www.infusion.com), a technology architect at
Boost.net (www.boost.net), and a freelance IT specialist, author, and developer. For the most part, he
immerses himself in .NET (in particular C# and lately WPF) and has written numerous books in the
field for several publishers. He specializes in communicating complex ideas in a way that is accessible
to anyone with a passion to learn, and spends much of his time playing with new technology to find
new things to teach people about.
During those (seemingly few) times where he isn’t doing the above, Karli will probably be wishing
he was hurtling down a mountain on a snowboard. Or possibly trying to get his novel published.
Either way, you’ll know him by his brightly colored clothes. You can also find him tweeting online at
www.twitter.com/karlequin, and maybe one day he’ll get around to making himself a website. Karli
authored chapters 1 through 14, 21, 25 and 26.
CHRISTIAN NAGEL is a Microsoft Regional Director and Microsoft MVP, an associate of Thinktecture,
and owner of CN Innovation. He is a software architect and developer who offers training and consulting on how to develop Microsoft .NET solutions. He looks back on more than 25 years of software
development experience. Christian started his computing career with PDP 11 and VAX/VMS systems,
covering a variety of languages and platforms. Since 2000, when .NET was just a technology preview,
he has been working with various .NET technologies to build numerous .NET solutions. With his profound knowledge of Microsoft technologies, he has written numerous .NET books, and is certified as a
Microsoft Certified Trainer and Professional Developer. Christian speaks at international conferences
such as TechEd and Tech Days, and started INETA Europe to support .NET user groups. You can
contact Christian via his web sites, www.cninnovation.com and www.thinktecture.com and follow his
tweets on www.twitter.com/christiannagel. Christian wrote chapters 17 through 20.
JACOB HAMMER PEDERSEN is a Senior Application Developer at Elbek & Vejrup. He just about started
programming when he was able to spell the word ‘BASIC’, which, incidentally is the first programming
language he ever used. He started programming the PC in the early ’90s, using Pascal but soon changed
his focus to C++, which still holds his interest. In the mid ’90s his focus changed again, this time to
Visual Basic. In the summer of 2000 he discovered C# and has been happily exploring it ever since.
Primarily working on the Microsoft platforms, his other expertise includes MS Office development,
SQL Server, COM and Visual Basic.Net.
A Danish citizen, Jacob works and lives in Aarhus, Denmark. He authored chapters 15, 16, and 22.
JON D. REID is a software engineering manager at Metrix LLC, an ISV of field service management software for the Microsoft environment. He has co-authored a variety .NET books, including Beginning
Visual C# 2008, Beginning C# Databases: From Novice to Professional, Pro Visual Studio .NET, and
many others. Jon wrote chapters 23 and
www.it-ebooks.info
ABOUT THE AUTHORS
MORGAN SKINNER began his computing career at a young age on the Sinclair ZX80 at school, where
he was underwhelmed by some code a teacher had written and so began programming in assembly
language. Since then he’s used all sorts of languages and platforms, including VAX Macro Assembler,
Pascal, Modula2, Smalltalk, X86 assembly language, PowerBuilder, C/C++, VB, and currently C#
(of course). He’s been programming in .NET since the PDC release in 2000, and liked it so much he
joined Microsoft in 2001. He now works in premier support for developers and spends most of his time
assisting customers with C#. Morgan wrapped up the book by authoring chapter 27. You can reach
Morgan at www.morganskinner.com.
x
www.it-ebooks.info
ABOUT THE TECHNICAL EDITOR
A ‘‘blue-badge’’ .NET architect and developer at Intel Corporation since March 2007, Doug Holland
is part of the Visual Computing Group and is presently working within an advanced tools and development team with an emphasis on chipset and driver testing. Doug Holland holds a Master’s Degree
in Software Engineering from Oxford University and has been awarded both the Microsoft MVP and
Intel Black Belt Developer awards. Outside of work, Doug enjoys spending time with his wife and four
children; and is also an officer in the Civil Air Patrol/U.S. Air Force Auxiliary. Beyond architecting and
developing software you can often find Doug at the local airport flying Cessnas over the California
landscape.
www.it-ebooks.info
www.it-ebooks.info
CREDITS
ACQUISITIONS EDITOR
VICE PRESIDENT AND EXECUTIVE
GROUP PUBLISHER
Paul Reese
Richard Swadley
DEVELOPMENT EDITOR
Maryann Steinhart
VICE PRESIDENT AND EXECUTIVE
PUBLISHER
PROJECT EDITOR
Barry Pruett
Ami Frank Sullivan
ASSOCIATE PUBLISHER
TECHNICAL EDITOR
Jim Minatel
Doug Holland
PROJECT COORDINATOR, COVER
Lynsey Stanford
PRODUCTION EDITOR
Rebecca Anderson
PROOFREADER
COPY EDITOR
Josh Chase, Word One
Luann Rouff
INDEXER
EDITORIAL DIRECTOR
J & J Indexing
Robyn B. Siesky
COVER DESIGNER
EDITORIAL MANAGER
Michael E. Trent
Mary Beth Wakefield
COVER IMAGE
ASSOCIATE DIRECTOR OF MARKETING
David Mayhew
PRODUCTION MANAGER
Tim Tate
www.it-ebooks.info
© Lisa Loyd/istockphoto
www.it-ebooks.info
ACKNOWLEDGMENTS
FROM KARLI WATSON: Thanks to all at Wiley for their support and assistance on this project, as well
as their understanding and flexibility in dealing with an author who never seems to have enough time
to write. Special thanks to my editor for this book, Ami Sullivan, for adding sparkle and making this
book shine. Also, thanks to friends, family, and work colleagues for understanding why I haven’t have
time for much socializing lately, and to Donna, as always, for all her support and for putting up with
all the late nights.
FROM CHRISTIAN NAGEL: To my two girls Angela and Stephanie. It’s great to have you. Thanks for
your great support and the big love you gave me during the hardest time of my life in 2009. Without
you I couldn’t have made it through. Stephanie, while not born yet, you were my biggest motivation
during that time. I love you both!
Also, a big thank you to my co-authors and the team at Wrox/Wiley for getting a great book out.
www.it-ebooks.info
www.it-ebooks.info
CONTENTS
INTRODUCTION
xxxiii
PART I: THE C# LANGUAGE
CHAPTER 1: INTRODUCING C#
3
What is the .NET Framework?
3
What’s in the .NET Framework?
Writing Applications Using the .NET Framework
CIL and JIT
Assemblies
Managed Code
Garbage Collection
Fitting It Together
Linking
What is C#?
4
5
5
5
6
6
7
8
8
Applications You Can Write with C#
C# in This Book
Visual Studio 2010
9
10
10
Visual Studio 2010 Express Products
Solutions
Summary
11
11
11
CHAPTER 2: WRITING A C# PROGRAM
13
The Development Environments
14
Visual Studio 2010
Visual C# 2010 Express Edition
14
17
Console Applications
18
The Solution Explorer
The Properties Window
The Error List Window
22
23
23
Windows Forms Applications
Summary
24
28
CHAPTER 3: VARIABLES AND EXPRESSIONS
as
31
32
www.it-ebooks.info
CONTENTS
Basic C# Console Application Structure
Variables
34
35
Simple Types
Variable Naming
Naming Conventions
Literal Values
String Literals
Variable Declaration and Assignment
36
40
41
42
43
44
Expressions
45
Mathematical Operators
Assignment Operators
Operator Precedence
Namespaces
45
50
51
51
Summary
55
CHAPTER 4: FLOW CONTROL
Boolean Logic
59
59
Boolean Assignment Operators
Bitwise Operators
Operator Precedence Updated
The goto Statement
Branching
62
64
68
68
69
The Ternary Operator
The if Statement
Checking More Conditions Using if Statements
The switch Statement
Looping
70
70
73
74
77
do Loops
while Loops
for Loops
Interrupting Loops
Infinite Loops
78
80
83
87
88
Summary
89
CHAPTER 5: MORE ABOUT VARIABLES
Type Conversion
93
94
Implicit Conversions
Explicit Conversions
Explicit Conversions Using the Convert Commands
Complex Variable Types
94
96
99
102
Enumerations
102
xviii
www.it-ebooks.info
CONTENTS
Defining Enumerations
Structs
Defining Structs
Arrays
Declaring Arrays
foreach Loops
Multidimensional Arrays
Arrays of Arrays
103
107
107
110
110
113
113
115
String Manipulation
Summary
116
121
CHAPTER 6: FUNCTIONS
125
Defining and Using Functions
126
Return Values
Parameters
Parameter Matching
Parameter Arrays
Reference and Value Parameters
Out Parameters
Variable Scope
128
130
132
132
134
136
137
Variable Scope in Other Structures
Parameters and Return Values versus Global Data
The Main() Function
Struct Functions
Overloading Functions
Delegates
Summary
140
142
143
146
147
149
152
CHAPTER 7: DEBUGGING AND ERROR HANDLING
Debugging in VS and VCE
155
156
Debugging in Nonbreak (Normal) Mode
Outputting Debugging Information
Tracepoints
Diagnostics Output Versus Tracepoints
Debugging in Break Mode
Entering Break Mode
Monitoring Variable Content
Stepping Through Code
Immediate and Command Windows
The Call Stack Window
Error Handling
157
158
163
164
166
166
170
172
173
174
175
try . . . catch . . . finally
176
xix
www.it-ebooks.info
CONTENTS
Listing and Configuring Exceptions
Notes on Exception Handling
Summary
181
182
183
CHAPTER 8: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
What Is Object-Oriented Programming?
What Is an Object?
Properties and Fields
Methods
Everything’s an Object
The Life Cycle of an Object
Constructors
Destructors
Static and Instance Class Members
Static Constructors
Static Classes
OOP Techniques
185
186
187
188
189
189
190
190
191
191
191
192
192
Interfaces
Disposable Objects
Inheritance
Polymorphism
Interface Polymorphism
Relationships Between Objects
Containment
Collections
Operator Overloading
Events
Reference Types Versus Value Types
193
194
194
196
197
198
198
199
200
200
201
OOP in Windows Applications
Summary
201
204
CHAPTER 9: DEFINING CLASSES
209
Class Definitions in C#
209
Interface Definitions
212
System.Object
Constructors and Destructors
Constructor Execution Sequence
215
217
218
OOP Tools in VS and VCE
222
The Class View Window
The Object Browser
Adding Classes
Class Diagrams
222
224
226
227
xx
www.it-ebooks.info
CONTENTS
Class Library Projects
Interfaces Versus Abstract Classes
Struct Types
Shallow Copying Versus Deep Copying
Summary
229
232
235
237
237
CHAPTER 10: DEFINING CLASS MEMBERS
241
Member Definitions
241
Defining Fields
Defining Methods
Defining Properties
Adding Members from a Class Diagram
Adding Methods
Adding Properties
Adding Fields
Refactoring Members
Automatic Properties
Additional Class Member Topics
Hiding Base Class Methods
Calling Overridden or Hidden Base Class Methods
The this Keyword
Nested Type Definitions
Interface Implementation
242
242
244
249
250
251
252
252
253
253
254
255
256
257
257
Implementing Interfaces in Classes
Explicit Interface Member Implementation
Adding Property Accessors with Nonpublic Accessibility
Partial Class Definitions
Partial Method Definitions
Example Application
258
260
260
261
262
264
Planning the Application
The Card Class
The Deck Class
Writing the Class Library
Adding the Suit and Rank Enumerations
Adding the Card Class
Adding the Deck Class
A Client Application for the Class Library
The Call Hierarchy Window
Summary
264
264
265
265
266
268
269
272
274
275
CHAPTER 11: COLLECTIONS, COMPARISONS, AND CONVERSIONS
Collections
277
278
xxi
www.it-ebooks.info
CONTENTS
Using Collections
Defining Collections
Indexers
Adding a Cards Collection to CardLib
Keyed Collections and IDictionary
Iterators
Iterators and Collections
Deep Copying
Adding Deep Copying to CardLib
Comparisons
278
284
286
288
291
293
297
299
301
303
Type Comparisons
Boxing and Unboxing
The is Operator
Value Comparisons
Operator Overloading
Adding Operator Overloads to CardLib
The IComparable and IComparer Interfaces
Sorting Collections Using the IComparable and IComparer Interfaces
Conversions
303
303
305
308
308
313
318
320
324
Overloading Conversion Operators
The as Operator
Summary
324
326
327
CHAPTER 12: GENERICS
331
What Are Generics?
Using Generics
332
333
Nullable Types
Operators and Nullable Types
The ?? Operator
The System.Collections.Generics Namespace
List<T>
Sorting and Searching Generic Lists
Dictionary<K, V>
Modifying CardLib to Use a Generic Collection Class
Defining Generic Types
333
334
336
340
341
343
349
350
351
Defining Generic Classes
The default Keyword
Constraining Types
Inheriting from Generic Classes
Generic Operators
Generic Structs
Defining Generic Interfaces
Defining Generic Methods
xxii
www.it-ebooks.info
351
354
354
361
362
363
364
364
CONTENTS
Defining Generic Delegates
366
Variance
366
Covariance
Contravariance
367
368
Summary
369
CHAPTER 13: ADDITIONAL OOP TECHNIQUES
The :: Operator and the Global Namespace Qualifier
Custom Exceptions
Adding Custom Exceptions to CardLib
Events
373
373
375
375
377
What Is an Event?
Handling Events
Defining Events
Multipurpose Event Handlers
The EventHandler and Generic EventHandler<T> Types
Return Values and Event Handlers
Anonymous Methods
Expanding and Using CardLib
377
378
380
385
388
388
389
389
A Card Game Client for CardLib
Summary
390
398
CHAPTER 14: C# LANGUAGE ENHANCEMENTS
Initializers
401
402
Object Initializers
Collection Initializers
402
404
Type Inference
Anonymous Types
Dynamic Lookup
407
409
413
The dynamic Type
IDynamicMetaObjectProvider
414
417
Advanced Method Parameters
418
Optional Parameters
Optional Parameter Values
Optional Parameter Order
Named Parameters
Named and Optional Parameter Guidelines
Extension Methods
Lambda Expressions
418
419
420
420
424
424
429
Anonymous Methods Recap
Lambda Expressions for Anonymous Methods
Lambda Expression Parameters
429
430
434
xxiii
www.it-ebooks.info