Ebook - Accelerated c# 2010 (apress)
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 orders-ny@springer-sbm.com, or visit http://www.springeronline.com. For information on translations, please e-mail info@apress.com, or visit http://www.apress.com. 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 http://www.apress.com/info/bulksales. 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 http://www.apress.com. You will need to answer questions pertaining to this book in order to successfully download the code. 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 . the copyright owner and the publisher. ISBN-13 (pbk): 97 8-1 -4 30 2-2 53 7-9 ISBN-13 (electronic): 97 8-1 -4 30 2-2 53 8-6 Printed and bound in the United States of. Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-8 00-SPRINGER, fax 20 1-3 4 8-4 505, e-mail orders-ny@springer-sbm.com,