www.it-ebooks.info
www.it-ebooks.info
C# 5.0 PROGRAMMER’S REFERENCE
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiii
▶▶ Part IThe C# Ecosystem
Chapter 1
The C# Environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Chapter 2
Writing a First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Chapter 3
Program and Code File Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
▶▶ Part II C# Language Elements
Chapter 4
Data Types, Variables, and Constants. . . . . . . . . . . . . . . . . . . . . . . . . 53
Chapter 5
Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Chapter 6
Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Chapter 7
Program Control Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Chapter 8
LINQ. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Chapter 9
Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Chapter 10 Tracing and Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
▶▶ Part III Object-Oriented Programming
Chapter 11 OOP Concepts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Chapter 12 Classes and Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Chapter 13 Namespaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
Chapter 14 Collection Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Chapter 15 Generics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
▶▶ Part IV Interacting with the Environment
Chapter 16 Printing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Chapter 17 Configuration and Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
Chapter 18 Streams. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
Chapter 19 File System Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
Chapter 20 Networking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
Continues
www.it-ebooks.info
▶▶ Part V Advanced Topics
Chapter 21 Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
Chapter 22 Parallel Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
Chapter 23 ADO.NET. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
Chapter 24 XML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
Chapter 25 Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
Chapter 26 Reflection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
Chapter 27 Cryptography. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
▶▶ Part VI Appendices
Appendix A Solutions to Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Appendix B Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733
Appendix C Variable Declarations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737
Appendix D Constant Declarations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 741
Appendix E Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 743
Appendix F Method Declarations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749
Appendix G Useful Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
Appendix H Control Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
Appendix I
Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 761
Appendix J LINQ. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763
Appendix K Classes and Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773
Appendix L Collection Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777
Appendix M Generic Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783
Appendix N Printing and Graphics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785
Appendix O Useful Exception Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 799
Appendix P Date and Time Format Specifiers. . . . . . . . . . . . . . . . . . . . . . . . . . . 803
Appendix Q Other Format Specifiers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807
Appendix R Streams. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813
Appendix S Filesystem Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821
Appendix T Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835
Appendix U Parallel Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 843
www.it-ebooks.info
Appendix V XML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849
Appendix W Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 859
Appendix X Reflection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 865
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 877
www.it-ebooks.info
www.it-ebooks.info
C# 5.0
Programmer’s Reference
www.it-ebooks.info
www.it-ebooks.info
C# 5.0
Programmer’s Reference
Rod Stephens
www.it-ebooks.info
C# 5.0 Programmer’s Reference
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2014 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-84728-2
ISBN: 978-1-118-84697-1 (ebk)
ISBN: 978-1-118-84729-9 (ebk)
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 publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such
as a CD or DVD that is not included in the version you purchased, you may download this material at . For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2014930410
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, 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. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.
www.it-ebooks.info
About the Author
Rod Stephens started out as a mathematician, but while studying at MIT, he
discovered how much fun programming is and has been programming professionally ever since. During his career, he has worked on an eclectic assortment
of applications in such fields as telephone switching, billing, repair dispatching,
tax processing, wastewater treatment, concert ticket sales, cartography, and
training for professional football players.
Rod has been a Microsoft Visual Basic Most Valuable Professional (MVP)
for more than 10 years and has taught introductory programming at ITT Technical Institute.
He has written more than two dozen books that have been translated into languages from all
over the world, and more than 250 magazine articles covering C#, Visual Basic, Visual Basic for
Applications, Delphi, and Java.
Rod’s popular C# Helper website (www.CSharpHelper.com) receives almost a million post visits per
year and contains thousands of pages of tips, tricks, and example programs for C# programmers, as
well as example code for this book. His VB Helper website (www.vb-helper.com) contains similar
material for Visual Basic programmers.
You can contact Rod at or
About the Technical Editor
Brian Hochgurtel has been doing .NET development for more than 10 years, and actually started
his .NET experience with Rod Stephens when they wrote the Wiley book Visual Basic .NET and
XML in 2002. Currently Brian works with C#, SQL Server, and SharePoint at Riverside Technology
in Fort Collins, CO.
www.it-ebooks.info
www.it-ebooks.info
Credits
Executive Editor
Vice President and
Executive Group Publisher
Robert Elliott
Richard Swadley
Project Editor
Adaobi Obi Tulton
Associate Publisher
Jim Minatel
Technical Editor
Brian Hochgurtel
Project Coordinator, Cover
Todd Klemme
Production Editor
Daniel Scribner
Compositor
Craig Woods, Happenstance Type-O-Rama
Copy Editor
San Dee Phillips
Proofreader
Nicole Hirschman
Manager of Content
Development and Assembly
Indexer
Mary Beth Wakefield
Johnna VanHoose Dinse
Director of Communit y Marketing
Cover Designer
David Mayhew
Wiley
Marketing Manager
Cover Image
Ashley Zurcher
©iStockphoto.com/W6
Business Manager
Amy Knies
www.it-ebooks.info
www.it-ebooks.info
Acknowledgments
Thanks to Bob Elliott, Adaobi Obi Tulton, John Mueller, San Dee Phillips, Daniel Scribner, and
all the others who worked so hard to make this book possible.
Thanks also to technical editor Brian Hochgurtel for giving me the benefit of his valuable experience.
www.it-ebooks.info
www.it-ebooks.info
Contents
xxxiii
xxxiv
xxxiv
xxxv
xxxvi
xxxvii
xxxviii
xxxviii
xxxix
xl
xl
xli
Introduction
xxxiii
Part I: The C# Ecosystem
Chapter 1: The C# Environment
Visual Studio
3
The C# Compiler
4
The CLR
6
The .NET Framework
8
Summary9
Exercises10
Chapter 2: Writing a First Program
3
3
4
6
8
9
10
11
11
14
16
19
21
23
24
3
11
Types of Projects
11
Console Applications
14
Windows Forms Applications
16
WPF Applications
19
Windows Store Applications
21
Summary23
Exercises24
Chapter 3: Program and Code File Structure
Hidden Files
Preprocessor Directives
27
28
31
#define and #undef
31
#if, #else, #elif, and #endif
33
#warning and #error
34
#line34
#region and #endregion
35
#pragma36
Code File Structure
37
The using Directive
The namespace Statement
Class Definitions
38
40
42
www.it-ebooks.info
CONTENTS
Comments43
End-of-line and Multiline Comments
XML Comments
43
45
Summary48
Exercises48
Part II: C# Language Elements
Chapter 4: Data Types, Variables, and Constants
Data Types
53
54
Value Versus Reference Types
The var Keyword
Variable Declaration Syntax
57
58
59
Name62
Attributes62
Accessibility63
Static, Constant, and Volatile Variables
64
Initialization65
Classes and Structures
66
Arrays67
Collections68
Literal Type Characters
Data Type Conversion
69
72
Implicit Conversion
73
Casting74
Using the as Operator
76
Casting Arrays
77
Parsing77
Using System.Convert
78
Using System.BitConverter
78
ToString79
Scope79
Block Scope
Method Scope
Class Scope
Restricting Scope
79
80
81
81
Parameter Declarations
82
By Value
By Reference
For Output
Unusual Circumstances and Exceptions
xvi
www.it-ebooks.info
82
83
84
85
CONTENTS
Properties86
Enumerations88
Nullable Types
92
Delegates93
Summary95
Exercises96
Chapter 5: Operators
99
Arithmetic Operators
100
Result Data Type
Shift Operators
Increment and Decrement Operators
Comparison Operators
Logical Operators
Bitwise Operators
Conditional and Null-coalescing Operators
Assignment Operators
Operator Precedence
The StringBuilder Class
DateTime and TimeSpan Operations
Operator Overloading
Comparison Operators
Logical Operators
Type Conversion Operators
100
101
101
102
103
105
106
107
108
110
111
112
113
115
115
Summary117
Exercises118
Chapter 6: Methods
121
Method Declarations
122
Attributes122
Accessibility124
Modifiers124
Name128
Return Type
128
Parameters129
Implementing Interfaces
133
Extension Methods
Lambda Expressions
135
136
Expression Lambdas
Statement Lambdas
Async Lambdas
136
137
138
xvii
www.it-ebooks.info
CONTENTS
Variance139
Asynchronous Methods
140
Calling EndInvoke Directly
Handling a Callback
Using Async and Await
140
141
144
Summary146
Exercises147
Chapter 7: Program Control Statements
Decision Statements
151
151
if-else Statements
switch Statements
Enumerated Values
Conditional and Null-coalescing Operators
Looping Statements
152
153
156
157
157
for Loops
157
Noninteger for Loops
159
while Loops
160
do Loops
161
foreach Loops
161
Enumerators163
Iterators164
break Statements
165
continue Statements
165
Summary166
Exercises166
Chapter 8: LINQ
169
Introduction to LINQ
Basic LINQ Query Syntax
171
173
from173
where174
orderby175
select175
Using LINQ Results
177
Advanced LINQ Query Syntax
178
join178
join into
179
group by
179
Aggregate Values
181
xviii
www.it-ebooks.info
CONTENTS
Set Methods
Limiting Results
182
183
Other LINQ Methods
LINQ Extension Methods
184
185
Method-Based Queries
Method-Based Queries with Lambda Functions
Extending LINQ
LINQ to Objects
LINQ to XML
185
187
188
189
189
XML Literals
LINQ into XML
LINQ out of XML
190
191
192
LINQ to ADO.NET
194
LINQ to SQL and LINQ to Entities
LINQ to DataSet
194
195
PLINQ198
Summary200
Exercises201
Chapter 9: Error Handling
Bugs Versus Undesirable Conditions
Catching Bugs
Code Contracts
Catching Undesirable Conditions
Global Exception Handling
try catch Blocks
205
206
206
209
213
216
220
Exception Objects
Throwing Exceptions
Rethrowing Exceptions
Custom Exceptions
223
224
226
227
Summary229
Exercises229
Chapter 10: Tracing and Debugging
231
The Debug Menu
232
234
The Debug ➪ Windows Submenu
The Breakpoints Window
235
The Immediate Window
237
Trace Listeners
238
Summary240
Exercises241
xix
www.it-ebooks.info
CONTENTS
Part III: Object-Oriented Programming
Chapter 11: OOP Concepts
245
Classes245
Encapsulation248
Inheritance250
Inheritance Hierarchies
251
Refinement and Abstraction
252
Has-a and Is-a Relationships
257
Adding and Modifying Class Features
257
Hiding and Overriding
258
abstract261
sealed262
Polymorphism263
Summary266
Exercises266
Chapter 12: Classes and Structures
269
Classes270
attributes270
accessibility271
abstract | sealed | static
272
partial273
Structures275
Value Versus Reference Types
Memory Requirements
Heap and Stack Performance
Object Assignment
Parameter Passing
Boxing and Unboxing
275
276
277
277
277
281
Constructors282
Structure Instantiation Details
285
Garbage Collection
286
Destructors286
Dispose288
Events290
Declaring Events
Raising Events
Catching Events
Using Event Delegate Types
Using Static Events
xx
www.it-ebooks.info
290
292
292
292
296
CONTENTS
Hiding and Overriding Events
Raising Parent Class Events
Implementing Custom Events
296
296
297
Static Methods
298
Summary300
Exercises301
Chapter 13: Namespaces
303
Collisions in .NET
The using Directive
304
304
Project Templates
Item Templates
307
309
The Default Namespace
311
Making Namespaces
311
Resolving Namespaces
313
The global Namespace
314
Summary315
Exercises315
Chapter 14: Collection Classes
317
Arrays318
Dimensions318
Lower Bounds
318
Resizing319
Speed320
Other Array Class Features
320
System.Collections321
ArrayList321
StringCollection324
NameValueCollection325
Dictionaries326
ListDictionary327
Hashtable328
HybridDictionary329
StringDictionary329
SortedList329
CollectionsUtil331
Stacks and Queues
331
Stack331
Queue333
xxi
www.it-ebooks.info
CONTENTS
Generic Collections
335
Collection Initializers
337
Iterators338
Summary339
Exercises340
Chapter 15: Generics
343
Advantages of Generics
Defining Generics
344
344
Generic Constructors
Multiple Types
Constrained Types
Default Values
345
346
348
352
Instantiating Generic Classes
352
Generic Collection Classes
352
Generic Methods
352
Generics and Extension Methods
353
Summary354
Exercises355
Part IV: Interacting with the Environment
Chapter 16: Printing
359
Windows Forms Printing
Basic Printing
Drawing Basics
359
360
365
WPF Printing
380
Using a Paginator
Creating Documents
381
385
Summary390
Exercises390
Chapter 17: Configuration and Resources
Environment Variables
393
394
Setting Environment Variables
Using System.Environment
394
395
Registry397
Configuration Files
402
xxii
www.it-ebooks.info
CONTENTS
Resource Files
405
Application Resources
Embedded Resources
Localization Resources
405
406
407
Summary408
Exercises408
Chapter 18: Streams
411
Stream412
FileStream414
MemoryStream415
BinaryReader and BinaryWriter
416
TextReader and TextWriter
418
StringReader and StringWriter
419
StreamReader and StreamWriter
421
Exists, OpenText, CreateText, and AppendText
422
Custom Stream Classes
423
Summary423
Exercises424
Chapter 19: File System Objects
Filesystem Permissions
.NET Framework Classes
425
426
426
Directory426
File428
DriveInfo430
DirectoryInfo431
FileInfo432
FileSystemWatcher434
Path436
Using the Recycle Bin
438
Using the FileIO.FileSystem Class
Using API Functions
Using Shell32.Shell
438
439
440
Summary443
Exercises444
xxiii
www.it-ebooks.info