Tải bản đầy đủ (.pdf) (67 trang)

accelerated c# 2010 trey nash phần 1 pot

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.28 MB, 67 trang )

Nash
Accelerated
C# 2010
Companion
eBook Available
this print for content only—size & color not accurate
  CYAN
  MAGENTA
  YELLOW
  BLACK
  PANTONE 123 C
BOOKS FOR PROFESSIONALS BY PROFESSIONALS
®
Trey Nash, author of
Accelerated C# 2008
Accelerated C# 2005
Accelerated VB 2005
(with Guy Fouche)
Accelerated VB 2008
(with Guy Fouche)
US $39.99
Shelve in:
.NET
User level:
Intermediate–Advanced
THE APRESS ROADMAP
Accelerated C# 2010
Pro C# 2010 and the
.NET 4.0 Platform
Pro LINQ: Language
Integrated Query in C# 2008


Beginning Android
Pro Android Games
Pro Android
www.apress.com
SOURCE CODE ONLINE
Companion eBook

See last page for details
on $10 eBook version
ISBN 978-1-4302-2537-9
9 781430 225379
5 39 9 9
Accelerated C# 2010
Dear Reader,
In your hands is a guide to creating effective C# 4.0 code. This book focuses precisely
on the C# language, showing you how to write programs that are robust, fault-toler-
ant, and ready to be put into widely available libraries.
I won’t burden your time with endless discussions of libraries: Accelerated C#
2010 instead presents you with a well organized, focused and easy to read text about
C# and all of the tried and true idioms, patterns, and design principles accrued in the
object oriented arena and during the lifetime of the .NET Framework. With many
short examples, I will show you how common design patterns are used routinely in
the .NET Framework and how you should employ them in your own designs.
I cover with you all the newer features of the C# language in detail - including
the dynamic type, co- and contra-variance, extension methods, lambda expres-
sions, and Language Integrated Query (LINQ) among others. The new dynamic
type facilitates interoperability possibilities that were previously cumbersome to
implement. Extension methods, lambda expressions, and LINQ foster a functional
programming model within a traditionally imperative programming language and
you’ll find that they expand your horizons and open up new possibilities of solu-

tions using functional programming techniques!
Another area of particular interest for C# developers is how we can write excep-
tion-safe and fault-tolerant code. The .NET Framework includes several facilities,
including Critical Execution Regions, to help protect the state of your application
in the event of an asynchronous exception. In this book, I explain how to use these
facilities to your advantage.
Have fun programming and remember, defining contract before implementa-
tion, striving to be exception neutral, applying performance analysis and optimiza-
tion, and being frugal with your resource usage are all keys to a successful product.

Trey Nash

7.5 x 9.25 spine = 1.21875" 656 page count
THE EXPERT’S VOICE
®
 IN C#

C# 2010
Trey Nash
The fast way to the latest and greatest in C#
programming and .NET 4.0
Accelerated

Accelerated C# 2010
















■ ■ ■
Trey Nash


Accelerated C# 2010
Copyright © 2010 by Trey Nash
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
ISBN-13 (pbk): 978-1-4302-2537-9
ISBN-13 (electronic): 978-1-4302-2538-6
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of
the trademark owner, with no intention of infringement of the trademark.
President and Publisher: Paul Manning
Lead Editor: Jonathan Hassell
Technical Reviewer: Damien Foggon
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell,
Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes,
Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft,

Matt Wade, Tom Welsh
Coordinating Editor: Mary Tobin
Copy Editors: Katie Stence and Nancy Sixsmith
Compositor: Bob Cooper
Indexer: Julie Grady
Artist: April Milne
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor,
New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail , or
visit .
For information on translations, please e-mail , or visit .
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our
Special Bulk Sales–eBook Licensing web page at
The information in this book is distributed on an “as is” basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have
any liability to any person or entity with respect to any loss or damage caused or alleged to be caused
directly or indirectly by the information contained in this work.
The source code for this book is available to readers at . You will need to answer
questions pertaining to this book in order to successfully download the code.



Dedicated to the memory of a special friend
Thor
January 1999 – October 2008





For Maite
for the love and support



v

Contents at a Glance
Contents vii
About the Author xxi
About the Technical Reviewer xxii
Acknowledgments xxiii
Preface xxiv
■Chapter 1: C# Preview 1
■Chapter 2: C# and the CLR 10
■Chapter 3: C# Syntax Overview 17
■Chapter 4: Classes, Structs, and Objects 43
■ Chapter 5: Interfaces and Contracts 137
■Chapter 6: Overloading Operators 165
■Chapter 7: Exception Handling and Exception Safety 181
■Chapter 8: Working with Strings 215
■Chapter 9: Arrays, Collection Types, and Iterators 243
■Chapter 10: Delegates, Anonymous Functions, and Events 279
■Chapter 11: Generics 307
■Chapter 12: Threading in C# 361
■Chapter 13: In Search of C# Canonical Forms 429
■Chaper 14: Extension Methods 489
■Chaper 15: Lambda Expressions 517
■Chaper 16: LINQ: Language Integrated Query 543



vi

■Chaper 17: Dynamic Types 577
Index 609

■ CONTENTS


vii

Contents
Contents at a Glance v
Contents vii
About the Author xxi
About the Technical Reviewer xxii
Acknowledgments xxiii
Preface xxiv
■Chapter 1: C# Preview 1
Differences Between C# and C++ 1
C# 1
C++ 2
CLR Garbage Collection 3
Example of a C# Program 3
Overview of Features Added in C# 2.0 5
Overview of Features Added in C# 3.0 6
Overview of New C# 4.0 Features 7
Summary 7
■Chapter 2: C# and the CLR 10
The JIT Compiler in the CLR 10

Assemblies and the Assembly Loader 11
Minimizing the Working Set of the Application 12
Naming Assemblies 12
Loading Assemblies 13
Metadata 13
■ CONTENTS


viii

Cross-Language Compatibility 15
Summary 15
■Chapter 3: C# Syntax Overview 17
C# Is a Strongly Typed Language 17
Expressions 18
Statements and Expressions 20
Types and Variables 21
Value Types 23
Enumerations 24
Flags Enumerations 25
Reference Types 26
Default Variable Initialization 27
Implicitly Typed Local Variables 28
Type Conversion 30
Array Covariance 31
Boxing Conversion 31
as and is Operators 32
Generics 34
Namespaces 35
Defining Namespaces 36

Using Namespaces 37
Control Flow 39
if-else, while, do-while, and for 39
switch 39
foreach 40
break, continue, goto, return, and throw 41
Summary 41
■ CONTENTS


ix

■Chapter 4: Classes, Structs, and Objects 43
Class Definitions 45
Fields 46
Constructors 49
Methods 49
Static Methods 50
Instance Methods 50
Properties 51
Declaring Properties 51
Accessors 53
Read-Only and Write-Only Properties 53
Auto-Implemented Properties 54
Encapsulation 56
Accessibility 59
Interfaces 61
Inheritance 62
Accessibility of Members 63
Implicit Conversion and a Taste of Polymorphism 63

Member Hiding 65
The base Keyword 68
sealed Classes 69
abstract Classes 70
Nested Classes 71
Indexers 74
partial Classes 76
partial Methods 77
Static Classes 79
Reserved Member Names 81
Reserved Names for Properties 81
Reserved Names for Indexers 81
Reserved Names for Destructors 82
■ CONTENTS


x

Reserved Names for Events 82
Value Type Definitions 82
Constructors 82
The Meaning of this 85
Finalizers 87
Interfaces 87
Anonymous Types 88
Object Initializers 91
Boxing and Unboxing 94
When Boxing Occurs 98
Efficiency and Confusion 100
System.Object 101

Equality and What It Means 103
The IComparable Interface 103
Creating Objects 103
The new Keyword 103
Using new with Value Types 103
Using new with Class Types 103
Field Initialization 104
Static (Class) Constructors 106
Instance Constructor and Creation Ordering 109
Destroying Objects 113
Finalizers 113
Deterministic Destruction 115
Exception Handling 115
Disposable Objects 116
The IDisposable Interface 116
The using Keyword 118
Method Parameter Types 119
Value Arguments 120
■ CONTENTS


xi

ref Arguments 120
out Parameters 122
param Arrays 123
Method Overloading 123
Optional Arguments 124
Named Arguments 125
Inheritance and Virtual Methods 128

Virtual and Abstract Methods 129
override and new Methods 129
sealed Methods 131
A Final Few Words on C# Virtual Methods 132
Inheritance, Containment, and Delegation 132
Choosing Between Interface and Class Inheritance 132
Delegation and Composition vs. Inheritance 134
Summary 136
■Chapter 5: Interfaces and Contracts 137
Interfaces Define Types 138
Defining Interfaces 139
What Can Be in an Interface? 139
Interface Inheritance and Member Hiding 140
Implementing Interfaces 143
Implicit Interface Implementation 143
Explicit Interface Implementation 143
Overriding Interface Implementations in Derived Classes 145
Beware of Side Effects of Value Types Implementing Interfaces 150
Interface Member Matching Rules 150
Explicit Interface Implementation with Value Types 154
Versioning Considerations 156
Contracts 157
■ CONTENTS


xii

Contracts Implemented with Classes 157
Interface Contracts 159
Choosing Between Interfaces and Classes 160

Summary 164
■Chapter 6: Overloading Operators 165
Just Because You Can Doesn’t Mean You Should 165
Types and Formats of Overloaded Operators 165
Operators Shouldn’t Mutate Their Operands 167
Does Parameter Order Matter? 167
Overloading the Addition Operator 168
Operators That Can Be Overloaded 169
Comparison Operators 170
Conversion Operators 173
Boolean Operators 176
Summary 179
■Chapter 7: Exception Handling and Exception Safety 181
How the CLR Treats Exceptions 181
Mechanics of Handling Exceptions in C# 182
Throwing Exceptions 182
Changes with Unhandled Exceptions Starting with .NET 2.0 182
Syntax Overview of the try, catch, and finally Statements 183
Rethrowing Exceptions and Translating Exceptions 186
Exceptions Thrown in finally Blocks 189
Exceptions Thrown in Finalizers 189
Exceptions Thrown in Static Constructors 191
Who Should Handle Exceptions? 192
Avoid Using Exceptions to Control Flow 193
Achieving Exception Neutrality 193
Basic Structure of Exception-Neutral Code 194
■ CONTENTS


xiii


Constrained Execution Regions 199
Critical Finalizers and SafeHandle 201
Creating Custom Exception Classes 206
Working with Allocated Resources and Exceptions 207
Providing Rollback Behavior 211
Summary 214
■Chapter 8: Working with Strings 215
String Overview 215
String Literals 216
Format Specifiers and Globalization 217
Object.ToString, IFormattable, and CultureInfo 218
Creating and Registering Custom CultureInfo Types 219
Format Strings 221
Console.WriteLine and String.Format 222
Examples of String Formatting in Custom Types 223
ICustomFormatter 224
Comparing Strings 227
Working with Strings from Outside Sources 228
StringBuilder 230
Searching Strings with Regular Expressions 232
Searching with Regular Expressions 232
Searching and Grouping 234
Replacing Text with Regex 238
Regex Creation Options 240
Summary 242
■Chapter 9: Arrays, Collection Types, and Iterators 243
Introduction to Arrays 243
Implicitly Typed Arrays 244
Type Convertibility and Covariance 247

■ CONTENTS


xiv

Sortability and Searchability 248
Synchronization 249
Vectors vs. Arrays 249
Multidimensional Rectangular Arrays 251
Multidimensional Jagged Arrays 253
Collection Types 255
Comparing ICollection<T> with ICollection 255
Collection Synchronization 257
Lists 258
Dictionaries 259
Sets 259
System.Collections.ObjectModel 260
Efficiency 262
IEnumerable<T>, IEnumerator<T>, IEnumerable, and IEnumerator 264
Types That Produce Collections 267
Iterators 268
Forward, Reverse, and Bidirectional Iterators 273
Collection Initializers 277
Summary 278
■Chapter 10: Delegates, Anonymous Functions, and Events 279
Overview of Delegates 279
Delegate Creation and Use 280
Single Delegate 281
Delegate Chaining 282
Iterating Through Delegate Chains 284

Unbound (Open Instance) Delegates 285
Events 288
Anonymous Methods 292
Captured Variables and Closures 295
■ CONTENTS


xv

Beware the Captured Variable Surprise 297
Anonymous Methods as Delegate Parameter Binders 300
The Strategy Pattern 304
Summary 305
■Chapter 11: Generics 307
Difference Between Generics and C++ Templates 308
Efficiency and Type Safety of Generics 309
Generic Type Definitions and Constructed Types 311
Generic Classes and Structs 311
Generic Interfaces 314
Generic Methods 315
Generic Delegates 317
Generic Type Conversion 320
Default Value Expression 321
Nullable Types 323
Constructed Types Control Accessibility 325
Generics and Inheritance 325
Constraints 327
Constraints on Nonclass Types 332
Co- and Contravariance 332
Covariance 334

Contravariance 337
Invariance 339
Variance and Delegates 340
Generic System Collections 344
Generic System Interfaces 345
Select Problems and Solutions 347
Conversion and Operators within Generic Types 347
Creating Constructed Types Dynamically 357
■ CONTENTS


xvi

Summary 358
■Chapter 12: Threading in C# 361
Threading in C# and .NET 361
Starting Threads 362
Passing Data to New Threads 363
Using ParameterizedThreadStart 365
The IOU Pattern and Asynchronous Method Calls 366
States of a Thread 366
Terminating Threads 369
Halting Threads and Waking Sleeping Threads 371
Waiting for a Thread to Exit 372
Foreground and Background Threads 372
Thread-Local Storage 373
How Unmanaged Threads and COM Apartments Fit In 377
Synchronizing Work Between Threads 378
Lightweight Synchronization with the Interlocked Class 379
SpinLock Class 385

Monitor Class 387
Beware of Boxing 391
Pulse and Wait 392
Locking Objects 396
ReaderWriterLock 397
ReaderWriterLockSlim 400
Mutex 401
Semaphore 402
Events 404
Win32 Synchronization Objects and WaitHandle 405
Using ThreadPool 407
Asynchronous Method Calls 408
Timers 416
■ CONTENTS


xvii

Concurrent Programming 417
Task Class 418
Parallel Class 420
Easy Entry to the Thread Pool 425
Thread-Safe Collection Classes 426
Summary 426
■Chapter 13: In Search of C# Canonical Forms 429
Reference Type Canonical Forms 429
Default to sealed Classes 430
Use the Non-Virtual Interface (NVI) Pattern 431
Is the Object Cloneable? 434
Is the Object Disposable? 440

Does the Object Need a Finalizer? 443
What Does Equality Mean for This Object? 450
Reference Types and Identity Equality 451
Value Equality 454
Overriding Object.Equals for Reference Types 454
If You Override Equals, Override GetHashCode Too 457
Does the Object Support Ordering? 461
Is the Object Formattable? 463
Is the Object Convertible? 467
Prefer Type Safety at All Times 469
Using Immutable Reference Types 473
Value Type Canonical Forms 476
Override Equals for Better Performance 477
Do Values of This Type Support Any Interfaces? 481
Implement Type-Safe Forms of Interface Members and Derived Methods 482
Summary 484
Checklist for Reference Types 485
Checklist for Value Types 486
■ CONTENTS


xviii

■Chaper 14: Extension Methods 489
Introduction to Extension Methods 489
How Does the Compiler Find Extension Methods? 490
Under the Covers 493
Code Readability versus Code Understandability 494
Recommendations for Use 495
Consider Extension Methods Over Inheritance 495

Isolate Extension Methods in Separate Namespace 496
Changing a Type’s Contract Can Break Extension Methods 497
Transforms 497
Operation Chaining 502
Custom Iterators 503
Borrowing from Functional Programming 505
The Visitor Pattern 511
Summary 515
■Chaper 15: Lambda Expressions 517
Introduction to Lambda Expressions 517
Lambda Expressions and Closures 518
Closures in C# 1.0 521
Closures in C# 2.0 523
Lambda Statements 524
Expression Trees 524
Operating on Expressions 527
Functions as Data 528
Useful Applications of Lambda Expressions 529
Iterators and Generators Revisited 529
More on Closures (Variable Capture) and Memoization 533
Currying 538
Anonymous Recursion 540
■ CONTENTS


xix

Summary 541
■Chaper 16: LINQ: Language Integrated Query 543
A Bridge to Data 544

Query Expressions 544
Extension Methods and Lambda Expressions Revisited 546
Standard Query Operators 547
C# Query Keywords 549
The from Clause and Range Variables 549
The join Clause 550
The where Clause and Filters 552
The orderby Clause 553
The select Clause and Projection 554
The let Clause 556
The group Clause 557
The into Clause and Continuations 560
The Virtues of Being Lazy 562
C# Iterators Foster Laziness 562
Subverting Laziness 563
Executing Queries Immediately 565
Expression Trees Revisited 566
Techniques from Functional Programming 566
Custom Standard Query Operators and Lazy Evaluation 566
Replacing foreach Statements 575
Summary 576
■Chaper 17: Dynamic Types 577
What does dynamic Mean? 577
How Does dynamic Work? 580
The Great Unification 582
Call Sites 582
■ CONTENTS


xx


Objects with Custom Dynamic Behavior 585
Efficiency 587
Boxing with Dynamic 589
Dynamic Conversions 590
Implicit Dynamic Expressions Conversion 591
Dynamic Overload Resolution 592
Dynamic Inheritance 594
You Cannot Derive from dynamic 595
You Cannot Implement dynamic Interfaces 595
You Can Derive From Dynamic Base Types 597
Duck Typing in C# 599
Limitations of dynamic Types 602
ExpandoObject: Creating Objects Dynamically 602
Summary 607
Index 609
■ CONTENTS


xxi

About the Author
■ Trey Nash is an Escalation Engineer at Microsoft on the Platforms Global
Escalation Services team working on the Windows operating systems as well as
various other products. When he is not working feverishly within the bowels of the
operating system, he is delivering training on .NET Platform debugging as well as
user mode and kernel mode debugging on the Windows platform. Prior to working
at Microsoft, he was a Principal Software Engineer working on security solutions at
Credant Technologies, a market-leading security software company. He also
enjoyed a stint at a large Bluetooth company developing Bluetooth solutions for

the release of Microsoft Vista. And before that he called Macromedia Inc. home for
five years. At Macromedia, he worked on a cross-product engineering team for
several years, designing solutions for a wide range of products throughout the
company, including Flash, Fireworks, and Dreamweaver. He specialized in
COM/DCOM using C/C++/ATL until the .NET revolution. He’s been glued to computers ever since he
scored his first, a TI-99/4A, when he was a mere 13 years old. He astounded his parents by turning a
childhood obsession into a decent paying career, much to their dismay. Trey received his bachelor of
science and his master of engineering degrees in electrical engineering from Texas A&M University.
When he’s not sitting in front of a computer, you can find him working in his garage, playing his piano,
brushing up on a foreign language (Russian and Icelandic are the current favorites), or playing ice
hockey.

■ CONTENTS


xxii

About the Technical Reviewer
■ Damien Foggon is a developer, writer, and technical reviewer in cutting-edge technologies and has
contributed to more than 50 books on .NET, C#, Visual Basic and ASP.NET. He is a multiple MCPD in
.NET 2.0 and .NET 3.5 and can be found online at .
■ CONTENTS


xxiii

Acknowledgments
Writing a book is a long and arduous process, during which I have received tons of great support, which I
greatly appreciate, from friends and family. The process would have been much more difficult, and
arguably much less fruitful, without their support.

I would like to specifically call out the following individuals for their contribution to the first two
editions of this work. I would like to thank (in no particular order) David Weller, Stephen Toub, Rex
Jaeschke, Vladimir Levin, Jerry Maresca, Chris Pels, Christopher T. McNabb, Brad Wilson, Peter Partch,
Paul Stubbs, Rufus Littlefield, Tomas Restrepo, John Lambert, Joan Murray, Sheri Cain, Jessica D’Amico,
Karen Gettman, Jim Huddleston, Richard Dal Porto, Gary Cornell, Brad Abrams, Ellie Fountain, Nicole
Abramowitz and the entire Apress crew, and finally, Shelley Nash, Michael Pulk, Shawn Wildermuth,
Sofia Marchant, Jim Compton, Dominic Shakeshaft, Wes Dyer, Kelly Winquist, and Laura Cheu.
During the development of the third edition, I would like to call out the following individuals for
their help and support (again in no particular order): Jonathan Hassell, Mary Tobin, Damien Foggon,
Maite Cervera.
If I have left anyone out, it is purely my mistake and not one I intended. I could not have done it
without all of your support. Thank you all!

×